authentik.enterprise.stages.source.stage

Source stage logic

  1"""Source stage logic"""
  2
  3from typing import Any
  4from uuid import uuid4
  5
  6from django.http import HttpRequest, HttpResponse
  7from django.utils.text import slugify
  8from django.utils.timezone import now
  9from guardian.shortcuts import get_anonymous_user
 10
 11from authentik.core.models import Source, User
 12from authentik.core.sources.flow_manager import (
 13    PLAN_CONTEXT_SOURCE_MATCH_FAILURE,
 14    PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG,
 15    SESSION_KEY_OVERRIDE_FLOW_TOKEN,
 16    SESSION_KEY_SOURCE_FLOW_CONTEXT,
 17    SESSION_KEY_SOURCE_FLOW_STAGES,
 18    MatchFailureConfig,
 19    clear_source_flow_session,
 20)
 21from authentik.core.types import UILoginButton
 22from authentik.enterprise.stages.source.models import SourceStage
 23from authentik.flows.challenge import Challenge, ChallengeResponse, HttpChallengeResponse
 24from authentik.flows.models import FlowToken, in_memory_stage
 25from authentik.flows.planner import PLAN_CONTEXT_IS_REDIRECTED, PLAN_CONTEXT_IS_RESTORED
 26from authentik.flows.stage import ChallengeStageView, StageView
 27from authentik.lib.utils.time import timedelta_from_string
 28
 29PLAN_CONTEXT_RESUME_TOKEN = "resume_token"  # nosec
 30
 31
 32class SourceStageView(ChallengeStageView):
 33    """Suspend the current flow execution and send the user to a source,
 34    after which this flow execution is resumed."""
 35
 36    login_button: UILoginButton
 37
 38    def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
 39        current_stage: SourceStage = self.executor.current_stage
 40        source: Source = (
 41            Source.objects.filter(pk=current_stage.source_id).select_subclasses().first()
 42        )
 43        if not source:
 44            self.logger.warning("Source does not exist")
 45            return self.executor.stage_invalid("Source does not exist")
 46        self.login_button = source.ui_login_button(self.request)
 47        if not self.login_button:
 48            self.logger.warning("Source does not have a UI login button")
 49            return self.executor.stage_invalid("Invalid source")
 50        restore_token = self.executor.plan.context.get(PLAN_CONTEXT_IS_RESTORED)
 51        override_token = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
 52        if restore_token and override_token and restore_token.pk == override_token.pk:
 53            clear_source_flow_session(self.request)
 54            self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
 55            return self.executor.stage_ok()
 56        return super().dispatch(request, *args, **kwargs)
 57
 58    def get_challenge(self, *args, **kwargs) -> Challenge:
 59        current_stage: SourceStage = self.executor.current_stage
 60        self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE, None)
 61        self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
 62        if current_stage.resume_on_match_failures:
 63            self.executor.plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG] = (
 64                MatchFailureConfig(
 65                    reasons=current_stage.resume_on_match_failures,
 66                    source_pk=str(current_stage.source_id),
 67                    stage_pk=str(current_stage.pk),
 68                )
 69            )
 70        resume_token = self.create_flow_token()
 71        self.request.session[SESSION_KEY_OVERRIDE_FLOW_TOKEN] = resume_token
 72        self.request.session[SESSION_KEY_SOURCE_FLOW_STAGES] = [in_memory_stage(SourceStageFinal)]
 73        self.request.session[SESSION_KEY_SOURCE_FLOW_CONTEXT] = {
 74            PLAN_CONTEXT_IS_REDIRECTED: self.executor.flow,
 75        }
 76        return self.login_button.challenge
 77
 78    def create_flow_token(self) -> FlowToken:
 79        """Save the current flow state in a token that can be used to resume this flow"""
 80        pending_user: User = self.get_pending_user()
 81        if pending_user.is_anonymous or not pending_user.pk:
 82            pending_user = get_anonymous_user()
 83        current_stage: SourceStage = self.executor.current_stage
 84        identifier = slugify(f"ak-source-stage-{current_stage.name}-{str(uuid4())}")
 85        # Don't check for validity here, we only care if the token exists
 86        tokens = FlowToken.objects.filter(identifier=identifier)
 87        valid_delta = timedelta_from_string(current_stage.resume_timeout)
 88        if not tokens.exists():
 89            return FlowToken.objects.create(
 90                expires=now() + valid_delta,
 91                user=pending_user,
 92                identifier=identifier,
 93                flow=self.executor.flow,
 94                _plan=FlowToken.pickle(self.executor.plan),
 95            )
 96        token = tokens.first()
 97        # Check if token is expired and rotate key if so
 98        if token.is_expired:
 99            token.expire_action()
100        return token
101
102    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
103        # Completion happens via dispatch(), not here.
104        return HttpChallengeResponse(self._get_challenge())
105
106
107class SourceStageFinal(StageView):
108    """Dynamic stage injected in the source flow manager. This is injected in the
109    flow the source flow manager picks (authentication or enrollment), and will run at the end.
110    This stage uses the override flow token to resume execution of the initial flow the
111    source stage is bound to."""
112
113    def dispatch(self, *args, **kwargs):
114        token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
115        if not token:
116            clear_source_flow_session(self.request)
117            return self.executor.stage_invalid("Flow token is invalid or expired")
118        try:
119            token.refresh_from_db()
120        except FlowToken.DoesNotExist:
121            clear_source_flow_session(self.request)
122            return self.executor.stage_invalid("Flow token is invalid or expired")
123        if token.is_expired:
124            token.expire_action()
125            clear_source_flow_session(self.request)
126            return self.executor.stage_invalid("Flow token is invalid or expired")
127        self.logger.info("Replacing source flow with overridden flow", flow=token.flow.slug)
128        plan = token.plan
129        plan.context.update(self.executor.plan.context)
130        plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
131        plan.context[PLAN_CONTEXT_IS_RESTORED] = token
132        response = plan.to_redirect(self.request, token.flow)
133        token.delete()
134        return response
PLAN_CONTEXT_RESUME_TOKEN = 'resume_token'
class SourceStageView(authentik.flows.stage.ChallengeStageView):
 33class SourceStageView(ChallengeStageView):
 34    """Suspend the current flow execution and send the user to a source,
 35    after which this flow execution is resumed."""
 36
 37    login_button: UILoginButton
 38
 39    def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
 40        current_stage: SourceStage = self.executor.current_stage
 41        source: Source = (
 42            Source.objects.filter(pk=current_stage.source_id).select_subclasses().first()
 43        )
 44        if not source:
 45            self.logger.warning("Source does not exist")
 46            return self.executor.stage_invalid("Source does not exist")
 47        self.login_button = source.ui_login_button(self.request)
 48        if not self.login_button:
 49            self.logger.warning("Source does not have a UI login button")
 50            return self.executor.stage_invalid("Invalid source")
 51        restore_token = self.executor.plan.context.get(PLAN_CONTEXT_IS_RESTORED)
 52        override_token = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
 53        if restore_token and override_token and restore_token.pk == override_token.pk:
 54            clear_source_flow_session(self.request)
 55            self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
 56            return self.executor.stage_ok()
 57        return super().dispatch(request, *args, **kwargs)
 58
 59    def get_challenge(self, *args, **kwargs) -> Challenge:
 60        current_stage: SourceStage = self.executor.current_stage
 61        self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE, None)
 62        self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
 63        if current_stage.resume_on_match_failures:
 64            self.executor.plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG] = (
 65                MatchFailureConfig(
 66                    reasons=current_stage.resume_on_match_failures,
 67                    source_pk=str(current_stage.source_id),
 68                    stage_pk=str(current_stage.pk),
 69                )
 70            )
 71        resume_token = self.create_flow_token()
 72        self.request.session[SESSION_KEY_OVERRIDE_FLOW_TOKEN] = resume_token
 73        self.request.session[SESSION_KEY_SOURCE_FLOW_STAGES] = [in_memory_stage(SourceStageFinal)]
 74        self.request.session[SESSION_KEY_SOURCE_FLOW_CONTEXT] = {
 75            PLAN_CONTEXT_IS_REDIRECTED: self.executor.flow,
 76        }
 77        return self.login_button.challenge
 78
 79    def create_flow_token(self) -> FlowToken:
 80        """Save the current flow state in a token that can be used to resume this flow"""
 81        pending_user: User = self.get_pending_user()
 82        if pending_user.is_anonymous or not pending_user.pk:
 83            pending_user = get_anonymous_user()
 84        current_stage: SourceStage = self.executor.current_stage
 85        identifier = slugify(f"ak-source-stage-{current_stage.name}-{str(uuid4())}")
 86        # Don't check for validity here, we only care if the token exists
 87        tokens = FlowToken.objects.filter(identifier=identifier)
 88        valid_delta = timedelta_from_string(current_stage.resume_timeout)
 89        if not tokens.exists():
 90            return FlowToken.objects.create(
 91                expires=now() + valid_delta,
 92                user=pending_user,
 93                identifier=identifier,
 94                flow=self.executor.flow,
 95                _plan=FlowToken.pickle(self.executor.plan),
 96            )
 97        token = tokens.first()
 98        # Check if token is expired and rotate key if so
 99        if token.is_expired:
100            token.expire_action()
101        return token
102
103    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
104        # Completion happens via dispatch(), not here.
105        return HttpChallengeResponse(self._get_challenge())

Suspend the current flow execution and send the user to a source, after which this flow execution is resumed.

def dispatch( self, request: django.http.request.HttpRequest, *args: Any, **kwargs: Any) -> django.http.response.HttpResponse:
39    def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
40        current_stage: SourceStage = self.executor.current_stage
41        source: Source = (
42            Source.objects.filter(pk=current_stage.source_id).select_subclasses().first()
43        )
44        if not source:
45            self.logger.warning("Source does not exist")
46            return self.executor.stage_invalid("Source does not exist")
47        self.login_button = source.ui_login_button(self.request)
48        if not self.login_button:
49            self.logger.warning("Source does not have a UI login button")
50            return self.executor.stage_invalid("Invalid source")
51        restore_token = self.executor.plan.context.get(PLAN_CONTEXT_IS_RESTORED)
52        override_token = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
53        if restore_token and override_token and restore_token.pk == override_token.pk:
54            clear_source_flow_session(self.request)
55            self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
56            return self.executor.stage_ok()
57        return super().dispatch(request, *args, **kwargs)
def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
59    def get_challenge(self, *args, **kwargs) -> Challenge:
60        current_stage: SourceStage = self.executor.current_stage
61        self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE, None)
62        self.executor.plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
63        if current_stage.resume_on_match_failures:
64            self.executor.plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG] = (
65                MatchFailureConfig(
66                    reasons=current_stage.resume_on_match_failures,
67                    source_pk=str(current_stage.source_id),
68                    stage_pk=str(current_stage.pk),
69                )
70            )
71        resume_token = self.create_flow_token()
72        self.request.session[SESSION_KEY_OVERRIDE_FLOW_TOKEN] = resume_token
73        self.request.session[SESSION_KEY_SOURCE_FLOW_STAGES] = [in_memory_stage(SourceStageFinal)]
74        self.request.session[SESSION_KEY_SOURCE_FLOW_CONTEXT] = {
75            PLAN_CONTEXT_IS_REDIRECTED: self.executor.flow,
76        }
77        return self.login_button.challenge

Return the challenge that the client should solve

def create_flow_token(self) -> authentik.flows.models.FlowToken:
 79    def create_flow_token(self) -> FlowToken:
 80        """Save the current flow state in a token that can be used to resume this flow"""
 81        pending_user: User = self.get_pending_user()
 82        if pending_user.is_anonymous or not pending_user.pk:
 83            pending_user = get_anonymous_user()
 84        current_stage: SourceStage = self.executor.current_stage
 85        identifier = slugify(f"ak-source-stage-{current_stage.name}-{str(uuid4())}")
 86        # Don't check for validity here, we only care if the token exists
 87        tokens = FlowToken.objects.filter(identifier=identifier)
 88        valid_delta = timedelta_from_string(current_stage.resume_timeout)
 89        if not tokens.exists():
 90            return FlowToken.objects.create(
 91                expires=now() + valid_delta,
 92                user=pending_user,
 93                identifier=identifier,
 94                flow=self.executor.flow,
 95                _plan=FlowToken.pickle(self.executor.plan),
 96            )
 97        token = tokens.first()
 98        # Check if token is expired and rotate key if so
 99        if token.is_expired:
100            token.expire_action()
101        return token

Save the current flow state in a token that can be used to resume this flow

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
103    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
104        # Completion happens via dispatch(), not here.
105        return HttpChallengeResponse(self._get_challenge())

Callback when the challenge has the correct format

class SourceStageFinal(authentik.flows.stage.StageView):
108class SourceStageFinal(StageView):
109    """Dynamic stage injected in the source flow manager. This is injected in the
110    flow the source flow manager picks (authentication or enrollment), and will run at the end.
111    This stage uses the override flow token to resume execution of the initial flow the
112    source stage is bound to."""
113
114    def dispatch(self, *args, **kwargs):
115        token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
116        if not token:
117            clear_source_flow_session(self.request)
118            return self.executor.stage_invalid("Flow token is invalid or expired")
119        try:
120            token.refresh_from_db()
121        except FlowToken.DoesNotExist:
122            clear_source_flow_session(self.request)
123            return self.executor.stage_invalid("Flow token is invalid or expired")
124        if token.is_expired:
125            token.expire_action()
126            clear_source_flow_session(self.request)
127            return self.executor.stage_invalid("Flow token is invalid or expired")
128        self.logger.info("Replacing source flow with overridden flow", flow=token.flow.slug)
129        plan = token.plan
130        plan.context.update(self.executor.plan.context)
131        plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
132        plan.context[PLAN_CONTEXT_IS_RESTORED] = token
133        response = plan.to_redirect(self.request, token.flow)
134        token.delete()
135        return response

Dynamic stage injected in the source flow manager. This is injected in the flow the source flow manager picks (authentication or enrollment), and will run at the end. This stage uses the override flow token to resume execution of the initial flow the source stage is bound to.

def dispatch(self, *args, **kwargs):
114    def dispatch(self, *args, **kwargs):
115        token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
116        if not token:
117            clear_source_flow_session(self.request)
118            return self.executor.stage_invalid("Flow token is invalid or expired")
119        try:
120            token.refresh_from_db()
121        except FlowToken.DoesNotExist:
122            clear_source_flow_session(self.request)
123            return self.executor.stage_invalid("Flow token is invalid or expired")
124        if token.is_expired:
125            token.expire_action()
126            clear_source_flow_session(self.request)
127            return self.executor.stage_invalid("Flow token is invalid or expired")
128        self.logger.info("Replacing source flow with overridden flow", flow=token.flow.slug)
129        plan = token.plan
130        plan.context.update(self.executor.plan.context)
131        plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
132        plan.context[PLAN_CONTEXT_IS_RESTORED] = token
133        response = plan.to_redirect(self.request, token.flow)
134        token.delete()
135        return response