Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions authentik/flows/challenge.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ class ContextualFlowInfo(PassiveSerializer):
cancel_url = CharField()
layout = ChoiceField(choices=[(x.value, x.name) for x in FlowLayout])
messages = FlowMessageSerializer(many=True, required=False)
continuous_login_hold = BooleanField(required=False)


class Challenge(PassiveSerializer):
Expand All @@ -84,6 +85,7 @@ class RedirectChallenge(Challenge):
# source-stage hops to an external IdP) stay False so the web client doesn't resume other
# continuous-login tabs prematurely. See web/src/flow/tabs/orchestrator.ts.
final_redirect = BooleanField(default=False)
continuous_login_hold = BooleanField(required=False)
component = CharField(default="xak-flow-redirect")


Expand Down
14 changes: 8 additions & 6 deletions authentik/flows/planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
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"
# Keep continuous-login tabs serialized through the provider authorization flow.
PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD = "goauthentik.io/flows/continuous_login_hold"
# Is set by the Flow Planner when a FlowToken was used, and the currently active flow plan
# was restored.
PLAN_CONTEXT_IS_RESTORED = "is_restored"
Expand Down Expand Up @@ -158,22 +160,22 @@ def to_redirect(
FlowExecutorView,
)

request.session[SESSION_KEY_PLAN] = self
requires_flow_executor = self.requires_flow_executor(allowed_silent_types)

if not requires_flow_executor:
# No unskippable stages found, so we can directly return the response of the last stage
# No unskippable stages found, so we can directly return the response of the last stage.
# The plan stays local to this request, so a flow running in another tab of the same
# session keeps its plan.
final_stage: type[StageView] = self.bindings[-1].stage.view
temp_exec = FlowExecutorView(flow=flow, request=request, plan=self)
temp_exec.direct_execution = True
temp_exec.current_stage = self.bindings[-1].stage
temp_exec.current_stage_view = final_stage
temp_exec.setup(request, flow.slug)
stage = final_stage(request=request, executor=temp_exec)
response = stage.dispatch(request)
# Ensure we clean the flow state we have in the session before we redirect away
temp_exec.stage_ok()
return response
return stage.dispatch(request)

request.session[SESSION_KEY_PLAN] = self
get_qs = request.GET.copy()
if request.user.is_authenticated and (
# Object-scoped permission or global permission
Expand Down
39 changes: 24 additions & 15 deletions authentik/flows/stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,12 @@
)
from authentik.flows.exceptions import StageInvalidException
from authentik.flows.models import Flow, InvalidResponseAction
from authentik.flows.planner import PLAN_CONTEXT_APPLICATION, PLAN_CONTEXT_PENDING_USER, FlowPlan
from authentik.flows.planner import (
PLAN_CONTEXT_APPLICATION,
PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD,
PLAN_CONTEXT_PENDING_USER,
FlowPlan,
)
from authentik.lib.avatars import DEFAULT_AVATAR, get_avatar
from authentik.lib.tracing import active_tracer
from authentik.lib.utils.reflection import class_to_path
Expand Down Expand Up @@ -209,20 +214,24 @@ def _get_challenge(self, *args, **kwargs) -> Challenge:
messages = get_messages(self.request)
# Flow payloads can outlive the previous signed media JWT, so
# refreshes must mint fresh URLs instead of reusing cached ones.
flow_info = ContextualFlowInfo(
data={
"title": format_flow_title(
self.executor.plan, self.executor.flow, self.request
),
"background": self.executor.flow.background_url(use_cache=False),
"background_themed_urls": self.executor.flow.background_themed_urls(
use_cache=False,
),
"cancel_url": self.cancel_url,
"layout": self.executor.flow.layout,
"messages": FlowMessageSerializer(messages, many=True).data,
},
)
flow_info_data = {
"title": format_flow_title(
self.executor.plan, self.executor.flow, self.request
),
"background": self.executor.flow.background_url(use_cache=False),
"background_themed_urls": self.executor.flow.background_themed_urls(
use_cache=False,
),
"cancel_url": self.cancel_url,
"layout": self.executor.flow.layout,
"messages": FlowMessageSerializer(messages, many=True).data,
}
plan_context = getattr(self.executor.plan, "context", {})
if PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD in plan_context:
flow_info_data["continuous_login_hold"] = plan_context[
PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD
]
flow_info = ContextualFlowInfo(data=flow_info_data)
flow_info.is_valid()
challenge.initial_data["flow_info"] = flow_info.data
if isinstance(challenge, WithUserInfoChallenge):
Expand Down
7 changes: 6 additions & 1 deletion authentik/flows/tests/test_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,12 @@
POLICY_RETURN_TRUE = MagicMock(return_value=PolicyResult(True))


def to_stage_response(request: HttpRequest, source: HttpResponse, final_redirect: bool = False):
def to_stage_response(
request: HttpRequest,
source: HttpResponse,
final_redirect: bool = False,
continuous_login_hold: bool | None = None,
):
"""Mock for to_stage_response that returns the original response, so we can check
inheritance and member attributes"""
return source
Expand Down
38 changes: 37 additions & 1 deletion authentik/flows/tests/test_planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from unittest.mock import MagicMock, Mock, PropertyMock, patch

from django.core.cache import cache
from django.http import HttpRequest
from django.http import HttpRequest, HttpResponseBadRequest, QueryDict
from django.shortcuts import redirect
from django.test import TestCase
from django.urls import reverse
Expand All @@ -29,10 +29,12 @@
PLAN_CONTEXT_IS_REDIRECTED,
PLAN_CONTEXT_IS_RESTORED,
PLAN_CONTEXT_PENDING_USER,
FlowPlan,
FlowPlanner,
cache_key,
)
from authentik.flows.stage import StageView
from authentik.flows.views.executor import SESSION_KEY_GET, SESSION_KEY_PLAN
from authentik.lib.generators import generate_id
from authentik.outposts.apps import MANAGED_OUTPOST
from authentik.outposts.models import Outpost
Expand Down Expand Up @@ -326,6 +328,40 @@ def dispatch(self, request: HttpRequest, *args, **kwargs):
"https://authentik.company",
)

def test_to_redirect_skip_keeps_session_plan(self):
"""Direct execution leaves the session's flow state to the flow that owns it, even when
the direct stage completes or cancels its plan."""
flow = create_test_flow()
flow.authentication = FlowAuthenticationRequirement.NONE
other_plan = FlowPlan(flow_pk=create_test_flow().pk.hex)
other_get = QueryDict("next=%2Fother%2F")

for completion in ["stage_ok", "cancel"]:
with self.subTest(completion=completion):
request = self.request_factory.get(
reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
)
request.session[SESSION_KEY_PLAN] = other_plan
request.session[SESSION_KEY_GET] = other_get
planner = FlowPlanner(flow)
planner.allow_empty_flows = True
plan = planner.plan(request)

class TStageView(StageView):
completion_method = completion

def dispatch(self, request: HttpRequest, *args, **kwargs):
getattr(self.executor, self.completion_method)()
return HttpResponseBadRequest()

plan.append_stage(in_memory_stage(TStageView))

response = plan.to_redirect(request, flow, allowed_silent_types=[TStageView])

self.assertEqual(response.status_code, 400)
self.assertIs(request.session[SESSION_KEY_PLAN], other_plan)
self.assertEqual(request.session[SESSION_KEY_GET], other_get)

def test_to_redirect_skip_stage(self):
"""Test to_redirect and skipping the flow executor
(with a stage bound that cannot be skipped)"""
Expand Down
17 changes: 17 additions & 0 deletions authentik/flows/tests/test_stage_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from authentik.core.tests.utils import RequestFactory as AuthentikRequestFactory
from authentik.core.tests.utils import create_test_flow
from authentik.flows.models import Flow, FlowStageBinding
from authentik.flows.planner import PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD, FlowPlan
from authentik.flows.stage import StageView
from authentik.flows.views.executor import FlowExecutorView
from authentik.lib.utils.reflection import all_subclasses
Expand Down Expand Up @@ -44,6 +45,22 @@ def test_challenge_stage_flow_info_uses_relative_background(self):
"/static/dist/assets/images/flow_background.jpg",
)

def test_challenge_stage_exposes_continuous_login_hold(self):
"""Challenge flow info exposes whether authorization must retain the tab lock."""
flow = create_test_flow()
stage = DummyStage.objects.create(name="dummy")
request = self.authentik_factory.get("/")
plan = FlowPlan(flow_pk=flow.pk.hex)
plan.context[PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD] = False
executor = FlowExecutorView(flow=flow, request=request, plan=plan)
executor.current_stage = stage
view = DummyStageView(executor)
view.request = request

challenge = view._get_challenge()

self.assertFalse(challenge.initial_data["flow_info"]["continuous_login_hold"])

def test_flow_interface_css_background_preserves_presigned_url_query(self):
"""Test flow CSS keeps signed URL query separators intact."""
flow = create_test_flow()
Expand Down
40 changes: 30 additions & 10 deletions authentik/flows/views/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
)
from authentik.flows.planner import (
CACHE_PREFIX,
PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD,
PLAN_CONTEXT_IS_RESTORED,
PLAN_CONTEXT_PENDING_USER,
PLAN_CONTEXT_REDIRECT,
Expand Down Expand Up @@ -111,6 +112,7 @@ class FlowExecutorView(APIView):
current_binding: FlowStageBinding | None = None
current_stage: Stage
current_stage_view: View
direct_execution = False

_logger: BoundLogger

Expand Down Expand Up @@ -400,6 +402,9 @@ def _flow_done(self) -> HttpResponse:
"""User Successfully passed all stages"""
# Since this is wrapped by the ExecutorShell, the next argument is saved in the session
# extract the next param before cancel as that cleans it
continuous_login_hold = None
if self.plan:
continuous_login_hold = self.plan.context.get(PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD)
if self.plan and PLAN_CONTEXT_REDIRECT in self.plan.context:
# The context `redirect` variable can only be set by
# an expression policy or authentik itself, so we don't
Expand All @@ -409,14 +414,18 @@ def _flow_done(self) -> HttpResponse:
self.request,
redirect(self.plan.context.get(PLAN_CONTEXT_REDIRECT)),
final_redirect=True,
continuous_login_hold=continuous_login_hold,
)
next_param = self.request.session.get(SESSION_KEY_GET, {}).get(
NEXT_ARG_NAME, "authentik_core:root-redirect"
)
self.cancel()
if next_param and not is_url_absolute(next_param):
return to_stage_response(
self.request, redirect_with_qs(next_param), final_redirect=True
self.request,
redirect_with_qs(next_param),
final_redirect=True,
continuous_login_hold=continuous_login_hold,
)
return to_stage_response(
self.request, self.stage_invalid(error_message=_("Invalid next URL"))
Expand All @@ -431,6 +440,11 @@ def stage_ok(self) -> HttpResponse:
)
if isinstance(self.current_stage_view, StageView):
self.current_stage_view.cleanup()
if self.direct_execution:
# The stage's own response is returned directly. The plan was never stored in the
# session, and the session may hold the plan of a flow running in another tab.
self.plan.pop()
return HttpResponse()
if self.flow.inspector_accessible(self.request):
self.request.session.get(SESSION_KEY_HISTORY, []).append(deepcopy(self.plan))
self.plan.pop()
Expand Down Expand Up @@ -480,6 +494,10 @@ def stage_invalid(self, error_message: str | None = None) -> HttpResponse:

def cancel(self):
"""Cancel current flow execution"""
if self.direct_execution:
# Direct execution keeps its plan local to the request, so there is no session
# state to clean up, and the session may belong to a flow running in another tab.
return
keys_to_delete = [
SESSION_KEY_PLAN,
SESSION_KEY_GET,
Expand Down Expand Up @@ -576,7 +594,10 @@ def dispatch(self, request: HttpRequest) -> HttpResponse:


def to_stage_response(
request: HttpRequest, source: HttpResponse, final_redirect: bool = False
request: HttpRequest,
source: HttpResponse,
final_redirect: bool = False,
continuous_login_hold: bool | None = None,
) -> HttpResponse:
"""Convert normal HttpResponse into JSON Response"""
if (
Expand All @@ -592,14 +613,13 @@ def to_stage_response(
to=str(redirect_url),
current=request.path,
)
return HttpChallengeResponse(
RedirectChallenge(
{
"to": str(redirect_url),
"final_redirect": final_redirect,
}
)
)
challenge_data = {
"to": str(redirect_url),
"final_redirect": final_redirect,
}
if continuous_login_hold is not None:
challenge_data["continuous_login_hold"] = continuous_login_hold
return HttpChallengeResponse(RedirectChallenge(challenge_data))
if isinstance(source, TemplateResponse):
return HttpChallengeResponse(
ShellChallenge(
Expand Down
25 changes: 25 additions & 0 deletions authentik/policies/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
create_test_user,
)
from authentik.flows.models import Flow, FlowDesignation
from authentik.flows.planner import PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD
from authentik.flows.views.executor import SESSION_KEY_PLAN
from authentik.lib.generators import generate_id
from authentik.policies.models import PolicyBinding
from authentik.policies.views import (
Expand Down Expand Up @@ -114,3 +116,26 @@ def get(self, *args, **kwargs):
res = TestView.as_view()(req)
self.assertEqual(res.status_code, 302)
self.assertEqual(res.url, "/if/flow/default-authentication-flow/?next=%2F")

@apply_blueprint("default/flow-default-authentication-flow.yaml")
def test_pav_continuous_login_hold_context(self):
"""Provider views can release continuous-login tabs after authentication."""
provider = Provider.objects.create(name=generate_id())
app = Application.objects.create(name=generate_id(), slug=generate_id(), provider=provider)
flow = Flow.objects.get(slug="default-authentication-flow")

class TestView(PolicyAccessView):
def resolve_provider_application(self):
self.provider = provider
self.application = app

def continuous_login_hold_required(self) -> bool:
return False

req = self.factory.get("/")
req.brand = create_test_brand(flow_authentication=flow)

response = TestView.as_view()(req)

self.assertEqual(response.status_code, 302)
self.assertFalse(req.session[SESSION_KEY_PLAN].context[PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD])
7 changes: 7 additions & 0 deletions authentik/policies/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from authentik.flows.models import Flow, FlowDesignation
from authentik.flows.planner import (
PLAN_CONTEXT_APPLICATION,
PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD,
PLAN_CONTEXT_POST,
FlowPlanner,
)
Expand Down Expand Up @@ -59,6 +60,10 @@ def resolve_provider_application(self):
is not caught, and will return directly"""
raise NotImplementedError

def continuous_login_hold_required(self) -> bool:
"""Keep other tabs paused until this provider's authorization flow finishes."""
return True

def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
try:
self.pre_permission_check()
Expand Down Expand Up @@ -91,6 +96,8 @@ def handle_no_permission(self) -> HttpResponse:
authn_flow = None
if self.application:
flow_context[PLAN_CONTEXT_APPLICATION] = self.application
if not self.continuous_login_hold_required():
flow_context[PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD] = False
if self.provider and self.provider.authentication_flow:
authn_flow = self.provider.authentication_flow
# Because this view might get hit with a POST request, we need to preserve that data
Expand Down
Loading
Loading