authentik.flows.planner

Flows Planner

  1"""Flows Planner"""
  2
  3from dataclasses import dataclass, field
  4from typing import TYPE_CHECKING, Any
  5
  6from django.core.cache import cache
  7from django.http import HttpRequest, HttpResponse
  8from django.utils.translation import gettext as _
  9from structlog.stdlib import BoundLogger, get_logger
 10
 11from authentik.core.models import User
 12from authentik.events.models import cleanse_dict
 13from authentik.flows.apps import HIST_FLOWS_PLAN_TIME
 14from authentik.flows.exceptions import EmptyFlowException, FlowNonApplicableException
 15from authentik.flows.markers import ReevaluateMarker, StageMarker
 16from authentik.flows.models import (
 17    Flow,
 18    FlowAuthenticationRequirement,
 19    FlowDesignation,
 20    FlowStageBinding,
 21    Stage,
 22    in_memory_stage,
 23)
 24from authentik.lib.config import CONFIG
 25from authentik.lib.tracing import Span, active_tracer
 26from authentik.lib.utils.urls import redirect_with_qs
 27from authentik.outposts.models import Outpost
 28from authentik.policies.engine import PolicyEngine
 29from authentik.policies.types import PolicyResult
 30from authentik.root.middleware import ClientIPMiddleware
 31
 32if TYPE_CHECKING:
 33    from authentik.flows.stage import StageView
 34
 35
 36LOGGER = get_logger()
 37PLAN_CONTEXT_PENDING_USER = "pending_user"
 38PLAN_CONTEXT_SSO = "is_sso"
 39PLAN_CONTEXT_REDIRECT = "redirect"
 40PLAN_CONTEXT_APPLICATION = "application"
 41PLAN_CONTEXT_DEVICE = "device"
 42PLAN_CONTEXT_SOURCE = "source"
 43PLAN_CONTEXT_OUTPOST = "outpost"
 44PLAN_CONTEXT_USER_SWITCH_FROM_USER = "user_switch_from_user"
 45PLAN_CONTEXT_USER_SWITCH_ADD_USER = "user_switch_add_user"
 46PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION = "user_switch_target_session"
 47PLAN_CONTEXT_POST = "goauthentik.io/http/post"
 48# Keep continuous-login tabs serialized through the provider authorization flow.
 49PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD = "goauthentik.io/flows/continuous_login_hold"
 50# Is set by the Flow Planner when a FlowToken was used, and the currently active flow plan
 51# was restored.
 52PLAN_CONTEXT_IS_RESTORED = "is_restored"
 53PLAN_CONTEXT_IS_REDIRECTED = "is_redirected"
 54PLAN_CONTEXT_REDIRECT_STAGE_TARGET = "redirect_stage_target"
 55CACHE_TIMEOUT = CONFIG.get_int("cache.timeout_flows")
 56CACHE_PREFIX = "goauthentik.io/flows/planner/"
 57
 58
 59def cache_key(flow: Flow, user: User | None = None) -> str:
 60    """Generate Cache key for flow"""
 61    prefix = CACHE_PREFIX + str(flow.pk)
 62    if user:
 63        prefix += f"#{user.pk}"
 64    return prefix
 65
 66
 67@dataclass(slots=True)
 68class FlowPlan:
 69    """This data-class is the output of a FlowPlanner. It holds a flat list
 70    of all Stages that should be run."""
 71
 72    flow_pk: str
 73
 74    bindings: list[FlowStageBinding] = field(default_factory=list)
 75    context: dict[str, Any] = field(default_factory=dict)
 76    markers: list[StageMarker] = field(default_factory=list)
 77
 78    def append_stage(self, stage: Stage, marker: StageMarker | None = None):
 79        """Append `stage` to the end of the plan, optionally with stage marker"""
 80        return self.append(FlowStageBinding(stage=stage), marker)
 81
 82    def append(self, binding: FlowStageBinding, marker: StageMarker | None = None):
 83        """Append `stage` to the end of the plan, optionally with stage marker"""
 84        self.bindings.append(binding)
 85        self.markers.append(marker or StageMarker())
 86
 87    def insert_stage(self, stage: Stage, marker: StageMarker | None = None, index=1):
 88        """Insert stage into plan, as immediate next stage"""
 89        self.bindings.insert(index, FlowStageBinding(stage=stage, order=0))
 90        self.markers.insert(index, marker or StageMarker())
 91
 92    def redirect(self, destination: str):
 93        """Insert a redirect stage as next stage"""
 94        from authentik.flows.stage import RedirectStage
 95
 96        self.insert_stage(in_memory_stage(RedirectStage, destination=destination))
 97
 98    def next(self, http_request: HttpRequest | None) -> FlowStageBinding | None:
 99        """Return next pending stage from the bottom of the list"""
100        if not self.has_stages:
101            return None
102        binding = self.bindings[0]
103        marker = self.markers[0]
104
105        if marker.__class__ is not StageMarker:
106            LOGGER.debug("f(plan_inst): stage has marker", binding=binding, marker=marker)
107        marked_stage = marker.process(self, binding, http_request)
108        if not marked_stage:
109            LOGGER.debug("f(plan_inst): marker returned none, next stage", binding=binding)
110            self.bindings.remove(binding)
111            self.markers.remove(marker)
112            if not self.has_stages:
113                return None
114
115            return self.next(http_request)
116        return marked_stage
117
118    def pop(self):
119        """Pop next pending stage from bottom of list"""
120        if not self.markers and not self.bindings:
121            return
122        self.markers.pop(0)
123        self.bindings.pop(0)
124
125    @property
126    def has_stages(self) -> bool:
127        """Check if there are any stages left in this plan"""
128        return len(self.markers) + len(self.bindings) > 0
129
130    def requires_flow_executor(
131        self,
132        allowed_silent_types: list[StageView] | None = None,
133    ):
134        # Check if we actually need to show the Flow executor, or if we can jump straight to the end
135        found_unskippable = True
136        if allowed_silent_types:
137            LOGGER.debug("Checking if we can skip the flow executor...")
138            # Policies applied to the flow have already been evaluated, so we're checking for stages
139            # allow-listed or bindings that require a policy re-eval
140            found_unskippable = False
141            for binding, marker in zip(self.bindings, self.markers, strict=True):
142                if binding.stage.view not in allowed_silent_types:
143                    found_unskippable = True
144                if marker and isinstance(marker, ReevaluateMarker):
145                    found_unskippable = True
146        LOGGER.debug("Required flow executor status", status=found_unskippable)
147        return found_unskippable
148
149    def to_redirect(
150        self,
151        request: HttpRequest,
152        flow: Flow,
153        next: str | None = None,
154        allowed_silent_types: list[StageView] | None = None,
155    ) -> HttpResponse:
156        """Redirect to the flow executor for this flow plan"""
157        from authentik.flows.views.executor import (
158            NEXT_ARG_NAME,
159            SESSION_KEY_PLAN,
160            FlowExecutorView,
161        )
162
163        requires_flow_executor = self.requires_flow_executor(allowed_silent_types)
164
165        if not requires_flow_executor:
166            # No unskippable stages found, so we can directly return the response of the last stage.
167            # The plan stays local to this request, so a flow running in another tab of the same
168            # session keeps its plan.
169            final_stage: type[StageView] = self.bindings[-1].stage.view
170            temp_exec = FlowExecutorView(flow=flow, request=request, plan=self)
171            temp_exec.direct_execution = True
172            temp_exec.current_stage = self.bindings[-1].stage
173            temp_exec.current_stage_view = final_stage
174            temp_exec.setup(request, flow.slug)
175            stage = final_stage(request=request, executor=temp_exec)
176            return stage.dispatch(request)
177
178        request.session[SESSION_KEY_PLAN] = self
179        get_qs = request.GET.copy()
180        if request.user.is_authenticated and (
181            # Object-scoped permission or global permission
182            request.user.has_perm("authentik_flows.inspect_flow", flow)
183            or request.user.has_perm("authentik_flows.inspect_flow")
184        ):
185            get_qs["inspector"] = "available"
186        if next:
187            get_qs[NEXT_ARG_NAME] = next
188
189        return redirect_with_qs(
190            "authentik_core:if-flow",
191            get_qs,
192            flow_slug=flow.slug,
193        )
194
195
196class FlowPlanner:
197    """Execute all policies to plan out a flat list of all Stages
198    that should be applied."""
199
200    use_cache: bool
201    allow_empty_flows: bool
202
203    flow: Flow
204
205    _logger: BoundLogger
206
207    def __init__(self, flow: Flow):
208        self.use_cache = True
209        self.allow_empty_flows = False
210        self.flow = flow
211        self._logger = get_logger().bind(flow_slug=flow.slug)
212
213    def _check_authentication(self, request: HttpRequest, context: dict[str, Any]):
214        """Check the flow's authentication level is matched by `request`"""
215        if (
216            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED
217            and not request.user.is_authenticated
218        ):
219            raise FlowNonApplicableException()
220        if (
221            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED
222            and request.user.is_authenticated
223            # Allow re-authenticating the current user (e.g. via a source for prompt=login)
224            and context.get(PLAN_CONTEXT_PENDING_USER) != request.user
225        ):
226            raise FlowNonApplicableException()
227        if (
228            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_SUPERUSER
229            and not request.user.is_superuser
230        ):
231            raise FlowNonApplicableException()
232        if (
233            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_REDIRECT
234            and context.get(PLAN_CONTEXT_IS_REDIRECTED) is None
235        ):
236            raise FlowNonApplicableException()
237        if (
238            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_TOKEN
239            and context.get(PLAN_CONTEXT_IS_RESTORED) is None
240        ):
241            raise FlowNonApplicableException(
242                PolicyResult(
243                    False, _("This link is invalid or has expired. Please request a new one.")
244                )
245            )
246        outpost_user = ClientIPMiddleware.get_outpost_user(request)
247        if self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_OUTPOST:
248            if not outpost_user:
249                raise FlowNonApplicableException()
250        if outpost_user:
251            outpost = Outpost.objects.filter(
252                # TODO: Since Outpost and user are not directly connected, we have to look up a user
253                # like this. This should ideally by in authentik/outposts/models.py
254                pk=outpost_user.username.replace("ak-outpost-", "")
255            ).first()
256            if outpost:
257                return {
258                    PLAN_CONTEXT_OUTPOST: {
259                        "instance": outpost,
260                    }
261                }
262        return {}
263
264    def plan(self, request: HttpRequest, default_context: dict[str, Any] | None = None) -> FlowPlan:
265        """Check each of the flows' policies, check policies for each stage with PolicyBinding
266        and return ordered list"""
267        with active_tracer().start_span(
268            op="authentik.flow.planner.plan", name=self.flow.slug
269        ) as span:
270            span: Span
271            span.set_data("flow", self.flow)
272            span.set_data("request", request)
273
274            self._logger.debug(
275                "f(plan): starting planning process",
276            )
277            context = default_context or {}
278            # Bit of a workaround here, if there is a pending user set in the default context
279            # we use that user for our cache key to make sure they don't get the generic response
280            if context and PLAN_CONTEXT_PENDING_USER in context:
281                user = context[PLAN_CONTEXT_PENDING_USER]
282            else:
283                user = request.user
284
285            context.update(self._check_authentication(request, context))
286            # First off, check the flow's direct policy bindings
287            # to make sure the user even has access to the flow
288            engine = PolicyEngine(self.flow, user, request)
289            engine.use_cache = self.use_cache
290            span.set_data("context", cleanse_dict(context))
291            engine.request.context.update(context)
292            engine.build()
293            result = engine.result
294            if not result.passing:
295                raise FlowNonApplicableException(result)
296            # User is passing so far, check if we have a cached plan
297            # Stage configuration plans are never cached
298            use_cache = (
299                self.use_cache and self.flow.designation != FlowDesignation.STAGE_CONFIGURATION
300            )
301            cached_plan_key = cache_key(self.flow, user)
302            cached_plan = cache.get(cached_plan_key, None) if use_cache else None
303            if cached_plan:
304                self._logger.debug(
305                    "f(plan): taking plan from cache",
306                    key=cached_plan_key,
307                )
308                # Reset the context as this isn't factored into caching
309                cached_plan.context = context
310                return cached_plan
311            self._logger.debug(
312                "f(plan): building plan",
313            )
314            plan = self._build_plan(user, request, context)
315            if use_cache:
316                cache.set(cache_key(self.flow, user), plan, CACHE_TIMEOUT)
317            if not plan.bindings and not self.allow_empty_flows:
318                raise EmptyFlowException()
319            return plan
320
321    def _build_plan(
322        self,
323        user: User,
324        request: HttpRequest,
325        default_context: dict[str, Any] | None,
326    ) -> FlowPlan:
327        """Build flow plan by checking each stage in their respective
328        order and checking the applied policies"""
329        with (
330            active_tracer().start_span(
331                op="authentik.flow.planner.build_plan",
332                name=self.flow.slug,
333            ) as span,
334            HIST_FLOWS_PLAN_TIME.labels(flow_slug=self.flow.slug).time(),
335        ):
336            span: Span
337            span.set_data("flow", self.flow)
338            span.set_data("user", user)
339            span.set_data("request", request)
340
341            plan = FlowPlan(flow_pk=self.flow.pk.hex)
342            if default_context:
343                plan.context = default_context
344            # Check Flow policies
345            bindings = list(
346                FlowStageBinding.objects.filter(target__pk=self.flow.pk).order_by("order")
347            )
348            stages = {
349                stage.pk: stage
350                for stage in Stage.objects.filter(
351                    pk__in=[binding.stage_id for binding in bindings]
352                ).select_subclasses()
353            }
354            for binding in bindings:
355                binding: FlowStageBinding
356                stage = stages[binding.stage_id]
357                # Cache the subclassed stage on the binding so it is pickled with the plan,
358                # otherwise every executor request re-queries it with all subclass joins
359                binding.stage = stage
360                marker = StageMarker()
361                if binding.evaluate_on_plan:
362                    self._logger.debug(
363                        "f(plan): evaluating on plan",
364                        stage=stage,
365                    )
366                    engine = PolicyEngine(binding, user, request)
367                    engine.use_cache = self.use_cache
368                    engine.request.context["flow_plan"] = plan
369                    engine.request.context.update(plan.context)
370                    engine.build()
371                    if engine.passing:
372                        self._logger.debug(
373                            "f(plan): stage passing",
374                            stage=stage,
375                        )
376                    else:
377                        stage = None
378                else:
379                    self._logger.debug(
380                        "f(plan): not evaluating on plan",
381                        stage=stage,
382                    )
383                if binding.re_evaluate_policies and stage:
384                    self._logger.debug(
385                        "f(plan): stage has re-evaluate marker",
386                        stage=stage,
387                    )
388                    marker = ReevaluateMarker(binding=binding)
389                if stage:
390                    plan.append(binding, marker)
391        self._logger.debug(
392            "f(plan): finished building",
393        )
394        return plan
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
PLAN_CONTEXT_PENDING_USER = 'pending_user'
PLAN_CONTEXT_SSO = 'is_sso'
PLAN_CONTEXT_REDIRECT = 'redirect'
PLAN_CONTEXT_APPLICATION = 'application'
PLAN_CONTEXT_DEVICE = 'device'
PLAN_CONTEXT_SOURCE = 'source'
PLAN_CONTEXT_OUTPOST = 'outpost'
PLAN_CONTEXT_USER_SWITCH_FROM_USER = 'user_switch_from_user'
PLAN_CONTEXT_USER_SWITCH_ADD_USER = 'user_switch_add_user'
PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION = 'user_switch_target_session'
PLAN_CONTEXT_POST = 'goauthentik.io/http/post'
PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD = 'goauthentik.io/flows/continuous_login_hold'
PLAN_CONTEXT_IS_RESTORED = 'is_restored'
PLAN_CONTEXT_IS_REDIRECTED = 'is_redirected'
PLAN_CONTEXT_REDIRECT_STAGE_TARGET = 'redirect_stage_target'
CACHE_TIMEOUT = 300
CACHE_PREFIX = 'goauthentik.io/flows/planner/'
def cache_key( flow: authentik.flows.models.Flow, user: authentik.core.models.User | None = None) -> str:
60def cache_key(flow: Flow, user: User | None = None) -> str:
61    """Generate Cache key for flow"""
62    prefix = CACHE_PREFIX + str(flow.pk)
63    if user:
64        prefix += f"#{user.pk}"
65    return prefix

Generate Cache key for flow

@dataclass(slots=True)
class FlowPlan:
 68@dataclass(slots=True)
 69class FlowPlan:
 70    """This data-class is the output of a FlowPlanner. It holds a flat list
 71    of all Stages that should be run."""
 72
 73    flow_pk: str
 74
 75    bindings: list[FlowStageBinding] = field(default_factory=list)
 76    context: dict[str, Any] = field(default_factory=dict)
 77    markers: list[StageMarker] = field(default_factory=list)
 78
 79    def append_stage(self, stage: Stage, marker: StageMarker | None = None):
 80        """Append `stage` to the end of the plan, optionally with stage marker"""
 81        return self.append(FlowStageBinding(stage=stage), marker)
 82
 83    def append(self, binding: FlowStageBinding, marker: StageMarker | None = None):
 84        """Append `stage` to the end of the plan, optionally with stage marker"""
 85        self.bindings.append(binding)
 86        self.markers.append(marker or StageMarker())
 87
 88    def insert_stage(self, stage: Stage, marker: StageMarker | None = None, index=1):
 89        """Insert stage into plan, as immediate next stage"""
 90        self.bindings.insert(index, FlowStageBinding(stage=stage, order=0))
 91        self.markers.insert(index, marker or StageMarker())
 92
 93    def redirect(self, destination: str):
 94        """Insert a redirect stage as next stage"""
 95        from authentik.flows.stage import RedirectStage
 96
 97        self.insert_stage(in_memory_stage(RedirectStage, destination=destination))
 98
 99    def next(self, http_request: HttpRequest | None) -> FlowStageBinding | None:
100        """Return next pending stage from the bottom of the list"""
101        if not self.has_stages:
102            return None
103        binding = self.bindings[0]
104        marker = self.markers[0]
105
106        if marker.__class__ is not StageMarker:
107            LOGGER.debug("f(plan_inst): stage has marker", binding=binding, marker=marker)
108        marked_stage = marker.process(self, binding, http_request)
109        if not marked_stage:
110            LOGGER.debug("f(plan_inst): marker returned none, next stage", binding=binding)
111            self.bindings.remove(binding)
112            self.markers.remove(marker)
113            if not self.has_stages:
114                return None
115
116            return self.next(http_request)
117        return marked_stage
118
119    def pop(self):
120        """Pop next pending stage from bottom of list"""
121        if not self.markers and not self.bindings:
122            return
123        self.markers.pop(0)
124        self.bindings.pop(0)
125
126    @property
127    def has_stages(self) -> bool:
128        """Check if there are any stages left in this plan"""
129        return len(self.markers) + len(self.bindings) > 0
130
131    def requires_flow_executor(
132        self,
133        allowed_silent_types: list[StageView] | None = None,
134    ):
135        # Check if we actually need to show the Flow executor, or if we can jump straight to the end
136        found_unskippable = True
137        if allowed_silent_types:
138            LOGGER.debug("Checking if we can skip the flow executor...")
139            # Policies applied to the flow have already been evaluated, so we're checking for stages
140            # allow-listed or bindings that require a policy re-eval
141            found_unskippable = False
142            for binding, marker in zip(self.bindings, self.markers, strict=True):
143                if binding.stage.view not in allowed_silent_types:
144                    found_unskippable = True
145                if marker and isinstance(marker, ReevaluateMarker):
146                    found_unskippable = True
147        LOGGER.debug("Required flow executor status", status=found_unskippable)
148        return found_unskippable
149
150    def to_redirect(
151        self,
152        request: HttpRequest,
153        flow: Flow,
154        next: str | None = None,
155        allowed_silent_types: list[StageView] | None = None,
156    ) -> HttpResponse:
157        """Redirect to the flow executor for this flow plan"""
158        from authentik.flows.views.executor import (
159            NEXT_ARG_NAME,
160            SESSION_KEY_PLAN,
161            FlowExecutorView,
162        )
163
164        requires_flow_executor = self.requires_flow_executor(allowed_silent_types)
165
166        if not requires_flow_executor:
167            # No unskippable stages found, so we can directly return the response of the last stage.
168            # The plan stays local to this request, so a flow running in another tab of the same
169            # session keeps its plan.
170            final_stage: type[StageView] = self.bindings[-1].stage.view
171            temp_exec = FlowExecutorView(flow=flow, request=request, plan=self)
172            temp_exec.direct_execution = True
173            temp_exec.current_stage = self.bindings[-1].stage
174            temp_exec.current_stage_view = final_stage
175            temp_exec.setup(request, flow.slug)
176            stage = final_stage(request=request, executor=temp_exec)
177            return stage.dispatch(request)
178
179        request.session[SESSION_KEY_PLAN] = self
180        get_qs = request.GET.copy()
181        if request.user.is_authenticated and (
182            # Object-scoped permission or global permission
183            request.user.has_perm("authentik_flows.inspect_flow", flow)
184            or request.user.has_perm("authentik_flows.inspect_flow")
185        ):
186            get_qs["inspector"] = "available"
187        if next:
188            get_qs[NEXT_ARG_NAME] = next
189
190        return redirect_with_qs(
191            "authentik_core:if-flow",
192            get_qs,
193            flow_slug=flow.slug,
194        )

This data-class is the output of a FlowPlanner. It holds a flat list of all Stages that should be run.

FlowPlan( flow_pk: str, bindings: list[authentik.flows.models.FlowStageBinding] = <factory>, context: dict[str, typing.Any] = <factory>, markers: list[authentik.flows.markers.StageMarker] = <factory>)
flow_pk: str
context: dict[str, typing.Any]
def append_stage( self, stage: authentik.flows.models.Stage, marker: authentik.flows.markers.StageMarker | None = None):
79    def append_stage(self, stage: Stage, marker: StageMarker | None = None):
80        """Append `stage` to the end of the plan, optionally with stage marker"""
81        return self.append(FlowStageBinding(stage=stage), marker)

Append stage to the end of the plan, optionally with stage marker

def append( self, binding: authentik.flows.models.FlowStageBinding, marker: authentik.flows.markers.StageMarker | None = None):
83    def append(self, binding: FlowStageBinding, marker: StageMarker | None = None):
84        """Append `stage` to the end of the plan, optionally with stage marker"""
85        self.bindings.append(binding)
86        self.markers.append(marker or StageMarker())

Append stage to the end of the plan, optionally with stage marker

def insert_stage( self, stage: authentik.flows.models.Stage, marker: authentik.flows.markers.StageMarker | None = None, index=1):
88    def insert_stage(self, stage: Stage, marker: StageMarker | None = None, index=1):
89        """Insert stage into plan, as immediate next stage"""
90        self.bindings.insert(index, FlowStageBinding(stage=stage, order=0))
91        self.markers.insert(index, marker or StageMarker())

Insert stage into plan, as immediate next stage

def redirect(self, destination: str):
93    def redirect(self, destination: str):
94        """Insert a redirect stage as next stage"""
95        from authentik.flows.stage import RedirectStage
96
97        self.insert_stage(in_memory_stage(RedirectStage, destination=destination))

Insert a redirect stage as next stage

def next( self, http_request: django.http.request.HttpRequest | None) -> authentik.flows.models.FlowStageBinding | None:
 99    def next(self, http_request: HttpRequest | None) -> FlowStageBinding | None:
100        """Return next pending stage from the bottom of the list"""
101        if not self.has_stages:
102            return None
103        binding = self.bindings[0]
104        marker = self.markers[0]
105
106        if marker.__class__ is not StageMarker:
107            LOGGER.debug("f(plan_inst): stage has marker", binding=binding, marker=marker)
108        marked_stage = marker.process(self, binding, http_request)
109        if not marked_stage:
110            LOGGER.debug("f(plan_inst): marker returned none, next stage", binding=binding)
111            self.bindings.remove(binding)
112            self.markers.remove(marker)
113            if not self.has_stages:
114                return None
115
116            return self.next(http_request)
117        return marked_stage

Return next pending stage from the bottom of the list

def pop(self):
119    def pop(self):
120        """Pop next pending stage from bottom of list"""
121        if not self.markers and not self.bindings:
122            return
123        self.markers.pop(0)
124        self.bindings.pop(0)

Pop next pending stage from bottom of list

has_stages: bool
126    @property
127    def has_stages(self) -> bool:
128        """Check if there are any stages left in this plan"""
129        return len(self.markers) + len(self.bindings) > 0

Check if there are any stages left in this plan

def requires_flow_executor(unknown):
131    def requires_flow_executor(
132        self,
133        allowed_silent_types: list[StageView] | None = None,
134    ):
135        # Check if we actually need to show the Flow executor, or if we can jump straight to the end
136        found_unskippable = True
137        if allowed_silent_types:
138            LOGGER.debug("Checking if we can skip the flow executor...")
139            # Policies applied to the flow have already been evaluated, so we're checking for stages
140            # allow-listed or bindings that require a policy re-eval
141            found_unskippable = False
142            for binding, marker in zip(self.bindings, self.markers, strict=True):
143                if binding.stage.view not in allowed_silent_types:
144                    found_unskippable = True
145                if marker and isinstance(marker, ReevaluateMarker):
146                    found_unskippable = True
147        LOGGER.debug("Required flow executor status", status=found_unskippable)
148        return found_unskippable
def to_redirect(unknown):
150    def to_redirect(
151        self,
152        request: HttpRequest,
153        flow: Flow,
154        next: str | None = None,
155        allowed_silent_types: list[StageView] | None = None,
156    ) -> HttpResponse:
157        """Redirect to the flow executor for this flow plan"""
158        from authentik.flows.views.executor import (
159            NEXT_ARG_NAME,
160            SESSION_KEY_PLAN,
161            FlowExecutorView,
162        )
163
164        requires_flow_executor = self.requires_flow_executor(allowed_silent_types)
165
166        if not requires_flow_executor:
167            # No unskippable stages found, so we can directly return the response of the last stage.
168            # The plan stays local to this request, so a flow running in another tab of the same
169            # session keeps its plan.
170            final_stage: type[StageView] = self.bindings[-1].stage.view
171            temp_exec = FlowExecutorView(flow=flow, request=request, plan=self)
172            temp_exec.direct_execution = True
173            temp_exec.current_stage = self.bindings[-1].stage
174            temp_exec.current_stage_view = final_stage
175            temp_exec.setup(request, flow.slug)
176            stage = final_stage(request=request, executor=temp_exec)
177            return stage.dispatch(request)
178
179        request.session[SESSION_KEY_PLAN] = self
180        get_qs = request.GET.copy()
181        if request.user.is_authenticated and (
182            # Object-scoped permission or global permission
183            request.user.has_perm("authentik_flows.inspect_flow", flow)
184            or request.user.has_perm("authentik_flows.inspect_flow")
185        ):
186            get_qs["inspector"] = "available"
187        if next:
188            get_qs[NEXT_ARG_NAME] = next
189
190        return redirect_with_qs(
191            "authentik_core:if-flow",
192            get_qs,
193            flow_slug=flow.slug,
194        )

Redirect to the flow executor for this flow plan

class FlowPlanner:
197class FlowPlanner:
198    """Execute all policies to plan out a flat list of all Stages
199    that should be applied."""
200
201    use_cache: bool
202    allow_empty_flows: bool
203
204    flow: Flow
205
206    _logger: BoundLogger
207
208    def __init__(self, flow: Flow):
209        self.use_cache = True
210        self.allow_empty_flows = False
211        self.flow = flow
212        self._logger = get_logger().bind(flow_slug=flow.slug)
213
214    def _check_authentication(self, request: HttpRequest, context: dict[str, Any]):
215        """Check the flow's authentication level is matched by `request`"""
216        if (
217            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED
218            and not request.user.is_authenticated
219        ):
220            raise FlowNonApplicableException()
221        if (
222            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED
223            and request.user.is_authenticated
224            # Allow re-authenticating the current user (e.g. via a source for prompt=login)
225            and context.get(PLAN_CONTEXT_PENDING_USER) != request.user
226        ):
227            raise FlowNonApplicableException()
228        if (
229            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_SUPERUSER
230            and not request.user.is_superuser
231        ):
232            raise FlowNonApplicableException()
233        if (
234            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_REDIRECT
235            and context.get(PLAN_CONTEXT_IS_REDIRECTED) is None
236        ):
237            raise FlowNonApplicableException()
238        if (
239            self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_TOKEN
240            and context.get(PLAN_CONTEXT_IS_RESTORED) is None
241        ):
242            raise FlowNonApplicableException(
243                PolicyResult(
244                    False, _("This link is invalid or has expired. Please request a new one.")
245                )
246            )
247        outpost_user = ClientIPMiddleware.get_outpost_user(request)
248        if self.flow.authentication == FlowAuthenticationRequirement.REQUIRE_OUTPOST:
249            if not outpost_user:
250                raise FlowNonApplicableException()
251        if outpost_user:
252            outpost = Outpost.objects.filter(
253                # TODO: Since Outpost and user are not directly connected, we have to look up a user
254                # like this. This should ideally by in authentik/outposts/models.py
255                pk=outpost_user.username.replace("ak-outpost-", "")
256            ).first()
257            if outpost:
258                return {
259                    PLAN_CONTEXT_OUTPOST: {
260                        "instance": outpost,
261                    }
262                }
263        return {}
264
265    def plan(self, request: HttpRequest, default_context: dict[str, Any] | None = None) -> FlowPlan:
266        """Check each of the flows' policies, check policies for each stage with PolicyBinding
267        and return ordered list"""
268        with active_tracer().start_span(
269            op="authentik.flow.planner.plan", name=self.flow.slug
270        ) as span:
271            span: Span
272            span.set_data("flow", self.flow)
273            span.set_data("request", request)
274
275            self._logger.debug(
276                "f(plan): starting planning process",
277            )
278            context = default_context or {}
279            # Bit of a workaround here, if there is a pending user set in the default context
280            # we use that user for our cache key to make sure they don't get the generic response
281            if context and PLAN_CONTEXT_PENDING_USER in context:
282                user = context[PLAN_CONTEXT_PENDING_USER]
283            else:
284                user = request.user
285
286            context.update(self._check_authentication(request, context))
287            # First off, check the flow's direct policy bindings
288            # to make sure the user even has access to the flow
289            engine = PolicyEngine(self.flow, user, request)
290            engine.use_cache = self.use_cache
291            span.set_data("context", cleanse_dict(context))
292            engine.request.context.update(context)
293            engine.build()
294            result = engine.result
295            if not result.passing:
296                raise FlowNonApplicableException(result)
297            # User is passing so far, check if we have a cached plan
298            # Stage configuration plans are never cached
299            use_cache = (
300                self.use_cache and self.flow.designation != FlowDesignation.STAGE_CONFIGURATION
301            )
302            cached_plan_key = cache_key(self.flow, user)
303            cached_plan = cache.get(cached_plan_key, None) if use_cache else None
304            if cached_plan:
305                self._logger.debug(
306                    "f(plan): taking plan from cache",
307                    key=cached_plan_key,
308                )
309                # Reset the context as this isn't factored into caching
310                cached_plan.context = context
311                return cached_plan
312            self._logger.debug(
313                "f(plan): building plan",
314            )
315            plan = self._build_plan(user, request, context)
316            if use_cache:
317                cache.set(cache_key(self.flow, user), plan, CACHE_TIMEOUT)
318            if not plan.bindings and not self.allow_empty_flows:
319                raise EmptyFlowException()
320            return plan
321
322    def _build_plan(
323        self,
324        user: User,
325        request: HttpRequest,
326        default_context: dict[str, Any] | None,
327    ) -> FlowPlan:
328        """Build flow plan by checking each stage in their respective
329        order and checking the applied policies"""
330        with (
331            active_tracer().start_span(
332                op="authentik.flow.planner.build_plan",
333                name=self.flow.slug,
334            ) as span,
335            HIST_FLOWS_PLAN_TIME.labels(flow_slug=self.flow.slug).time(),
336        ):
337            span: Span
338            span.set_data("flow", self.flow)
339            span.set_data("user", user)
340            span.set_data("request", request)
341
342            plan = FlowPlan(flow_pk=self.flow.pk.hex)
343            if default_context:
344                plan.context = default_context
345            # Check Flow policies
346            bindings = list(
347                FlowStageBinding.objects.filter(target__pk=self.flow.pk).order_by("order")
348            )
349            stages = {
350                stage.pk: stage
351                for stage in Stage.objects.filter(
352                    pk__in=[binding.stage_id for binding in bindings]
353                ).select_subclasses()
354            }
355            for binding in bindings:
356                binding: FlowStageBinding
357                stage = stages[binding.stage_id]
358                # Cache the subclassed stage on the binding so it is pickled with the plan,
359                # otherwise every executor request re-queries it with all subclass joins
360                binding.stage = stage
361                marker = StageMarker()
362                if binding.evaluate_on_plan:
363                    self._logger.debug(
364                        "f(plan): evaluating on plan",
365                        stage=stage,
366                    )
367                    engine = PolicyEngine(binding, user, request)
368                    engine.use_cache = self.use_cache
369                    engine.request.context["flow_plan"] = plan
370                    engine.request.context.update(plan.context)
371                    engine.build()
372                    if engine.passing:
373                        self._logger.debug(
374                            "f(plan): stage passing",
375                            stage=stage,
376                        )
377                    else:
378                        stage = None
379                else:
380                    self._logger.debug(
381                        "f(plan): not evaluating on plan",
382                        stage=stage,
383                    )
384                if binding.re_evaluate_policies and stage:
385                    self._logger.debug(
386                        "f(plan): stage has re-evaluate marker",
387                        stage=stage,
388                    )
389                    marker = ReevaluateMarker(binding=binding)
390                if stage:
391                    plan.append(binding, marker)
392        self._logger.debug(
393            "f(plan): finished building",
394        )
395        return plan

Execute all policies to plan out a flat list of all Stages that should be applied.

FlowPlanner(flow: authentik.flows.models.Flow)
208    def __init__(self, flow: Flow):
209        self.use_cache = True
210        self.allow_empty_flows = False
211        self.flow = flow
212        self._logger = get_logger().bind(flow_slug=flow.slug)
use_cache: bool
allow_empty_flows: bool
def plan( self, request: django.http.request.HttpRequest, default_context: dict[str, Any] | None = None) -> FlowPlan:
265    def plan(self, request: HttpRequest, default_context: dict[str, Any] | None = None) -> FlowPlan:
266        """Check each of the flows' policies, check policies for each stage with PolicyBinding
267        and return ordered list"""
268        with active_tracer().start_span(
269            op="authentik.flow.planner.plan", name=self.flow.slug
270        ) as span:
271            span: Span
272            span.set_data("flow", self.flow)
273            span.set_data("request", request)
274
275            self._logger.debug(
276                "f(plan): starting planning process",
277            )
278            context = default_context or {}
279            # Bit of a workaround here, if there is a pending user set in the default context
280            # we use that user for our cache key to make sure they don't get the generic response
281            if context and PLAN_CONTEXT_PENDING_USER in context:
282                user = context[PLAN_CONTEXT_PENDING_USER]
283            else:
284                user = request.user
285
286            context.update(self._check_authentication(request, context))
287            # First off, check the flow's direct policy bindings
288            # to make sure the user even has access to the flow
289            engine = PolicyEngine(self.flow, user, request)
290            engine.use_cache = self.use_cache
291            span.set_data("context", cleanse_dict(context))
292            engine.request.context.update(context)
293            engine.build()
294            result = engine.result
295            if not result.passing:
296                raise FlowNonApplicableException(result)
297            # User is passing so far, check if we have a cached plan
298            # Stage configuration plans are never cached
299            use_cache = (
300                self.use_cache and self.flow.designation != FlowDesignation.STAGE_CONFIGURATION
301            )
302            cached_plan_key = cache_key(self.flow, user)
303            cached_plan = cache.get(cached_plan_key, None) if use_cache else None
304            if cached_plan:
305                self._logger.debug(
306                    "f(plan): taking plan from cache",
307                    key=cached_plan_key,
308                )
309                # Reset the context as this isn't factored into caching
310                cached_plan.context = context
311                return cached_plan
312            self._logger.debug(
313                "f(plan): building plan",
314            )
315            plan = self._build_plan(user, request, context)
316            if use_cache:
317                cache.set(cache_key(self.flow, user), plan, CACHE_TIMEOUT)
318            if not plan.bindings and not self.allow_empty_flows:
319                raise EmptyFlowException()
320            return plan

Check each of the flows' policies, check policies for each stage with PolicyBinding and return ordered list