From 3211fa01158b2f34a3448b8cef6c0779dcdb2ea1 Mon Sep 17 00:00:00 2001 From: Ryan Pesek <44002516+ryanpesek@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:16:30 -0600 Subject: [PATCH] providers/saml: skip empty authorization flows for saml providers (#25417) * providers/saml: skip empty authorization flows for saml providers Closes #24878 * providers/saml: localize direct POST page, note skipped authorization flows --------- Co-authored-by: Teffen Ellis Co-authored-by: Jacob Sachs --- authentik/flows/challenge.py | 2 + authentik/flows/planner.py | 14 +- authentik/flows/stage.py | 39 ++- authentik/flows/tests/test_executor.py | 7 +- authentik/flows/tests/test_planner.py | 38 ++- authentik/flows/tests/test_stage_views.py | 17 + authentik/flows/views/executor.py | 40 ++- authentik/policies/tests/test_views.py | 25 ++ authentik/policies/views.py | 7 + .../saml/templates/if/saml_form_post.html | 19 ++ .../saml/tests/test_auth_n_request.py | 300 +++++++++++++++++- authentik/providers/saml/views/flows.py | 28 +- authentik/providers/saml/views/sso.py | 16 +- .../client-go/model_contextual_flow_info.go | 37 +++ .../client-go/model_redirect_challenge.go | 37 +++ .../src/models/contextual_flow_info.rs | 6 + .../src/models/redirect_challenge.rs | 6 + .../src/models/ContextualFlowInfo.ts | 4 + .../client-ts/src/models/RedirectChallenge.ts | 4 + schema.yml | 4 + .../controllers/FlowMultitabController.ts | 9 +- web/src/flow/stages/RedirectStage.ts | 16 +- web/src/flow/tabs/broadcast.ts | 4 + web/src/flow/tabs/continuous-login.ts | 13 + web/src/flow/tabs/orchestrator.ts | 4 + web/test/unit/continuous-login.test.ts | 29 ++ website/docs/releases/2026/v2026.11/index.mdx | 1 + 27 files changed, 677 insertions(+), 49 deletions(-) create mode 100644 authentik/providers/saml/templates/if/saml_form_post.html create mode 100644 web/src/flow/tabs/continuous-login.ts create mode 100644 web/test/unit/continuous-login.test.ts diff --git a/authentik/flows/challenge.py b/authentik/flows/challenge.py index 1c4be6ff0bb0..ec2d16cbb556 100644 --- a/authentik/flows/challenge.py +++ b/authentik/flows/challenge.py @@ -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): @@ -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") diff --git a/authentik/flows/planner.py b/authentik/flows/planner.py index cbdb84d34bae..9a05f9984d1d 100644 --- a/authentik/flows/planner.py +++ b/authentik/flows/planner.py @@ -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" @@ -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 diff --git a/authentik/flows/stage.py b/authentik/flows/stage.py index 085ff15450f3..12f6c0f2e7f8 100644 --- a/authentik/flows/stage.py +++ b/authentik/flows/stage.py @@ -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 @@ -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): diff --git a/authentik/flows/tests/test_executor.py b/authentik/flows/tests/test_executor.py index 785e48a1afe0..787b3e711593 100644 --- a/authentik/flows/tests/test_executor.py +++ b/authentik/flows/tests/test_executor.py @@ -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 diff --git a/authentik/flows/tests/test_planner.py b/authentik/flows/tests/test_planner.py index ed4502269daf..d384d067151c 100644 --- a/authentik/flows/tests/test_planner.py +++ b/authentik/flows/tests/test_planner.py @@ -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 @@ -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 @@ -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)""" diff --git a/authentik/flows/tests/test_stage_views.py b/authentik/flows/tests/test_stage_views.py index 458d2378031d..42f4eef50a5d 100644 --- a/authentik/flows/tests/test_stage_views.py +++ b/authentik/flows/tests/test_stage_views.py @@ -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 @@ -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() diff --git a/authentik/flows/views/executor.py b/authentik/flows/views/executor.py index 918b79100969..40e8d6f4c7eb 100644 --- a/authentik/flows/views/executor.py +++ b/authentik/flows/views/executor.py @@ -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, @@ -111,6 +112,7 @@ class FlowExecutorView(APIView): current_binding: FlowStageBinding | None = None current_stage: Stage current_stage_view: View + direct_execution = False _logger: BoundLogger @@ -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 @@ -409,6 +414,7 @@ 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" @@ -416,7 +422,10 @@ def _flow_done(self) -> HttpResponse: 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")) @@ -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() @@ -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, @@ -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 ( @@ -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( diff --git a/authentik/policies/tests/test_views.py b/authentik/policies/tests/test_views.py index 2a61f270adf6..98828f9bc736 100644 --- a/authentik/policies/tests/test_views.py +++ b/authentik/policies/tests/test_views.py @@ -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 ( @@ -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]) diff --git a/authentik/policies/views.py b/authentik/policies/views.py index 02d21aabec5f..82e51fe8c642 100644 --- a/authentik/policies/views.py +++ b/authentik/policies/views.py @@ -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, ) @@ -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() @@ -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 diff --git a/authentik/providers/saml/templates/if/saml_form_post.html b/authentik/providers/saml/templates/if/saml_form_post.html new file mode 100644 index 000000000000..56100aeed241 --- /dev/null +++ b/authentik/providers/saml/templates/if/saml_form_post.html @@ -0,0 +1,19 @@ +{% load i18n %}{% get_current_language as LANGUAGE_CODE %} + + + + + {% trans "Redirecting..." %} + + +
+ {% for key, value in attrs.items %} + + {% endfor %} + +
+ + diff --git a/authentik/providers/saml/tests/test_auth_n_request.py b/authentik/providers/saml/tests/test_auth_n_request.py index 620daa628d6a..993fc3e439aa 100644 --- a/authentik/providers/saml/tests/test_auth_n_request.py +++ b/authentik/providers/saml/tests/test_auth_n_request.py @@ -3,6 +3,7 @@ import tracemalloc from base64 import b64encode from json import loads +from unittest.mock import patch from urllib.parse import parse_qs, urlparse from defusedxml.lxml import fromstring @@ -40,17 +41,27 @@ from authentik.events.models import Event, EventAction from authentik.flows.apps import ContinuousLogin from authentik.flows.models import FlowStageBinding +from authentik.flows.planner import PLAN_CONTEXT_APPLICATION +from authentik.flows.views.executor import SESSION_KEY_GET, SESSION_KEY_PLAN from authentik.lib.generators import generate_id from authentik.lib.xml import lxml_from_string -from authentik.providers.saml.models import SAMLBindings, SAMLPropertyMapping, SAMLProvider +from authentik.policies.dummy.models import DummyPolicy +from authentik.policies.models import PolicyBinding +from authentik.providers.saml.models import ( + SAMLBindings, + SAMLPropertyMapping, + SAMLProvider, + SAMLSession, +) from authentik.providers.saml.processors.assertion import AssertionProcessor from authentik.providers.saml.processors.authn_request_parser import AuthNRequestParser from authentik.providers.saml.utils.encoding import deflate_and_base64_encode from authentik.providers.saml.views.sso import SESSION_KEY_LAST_LOGIN_UID -from authentik.sources.saml.exceptions import MismatchedRequestID +from authentik.sources.saml.exceptions import MismatchedRequestID, SAMLException from authentik.sources.saml.models import SAMLBindingTypes, SAMLSource from authentik.sources.saml.processors.request import SESSION_KEY_REQUEST_ID, RequestProcessor from authentik.sources.saml.processors.response import ResponseProcessor +from authentik.stages.consent.models import ConsentStage from authentik.stages.dummy.models import DummyStage POST_REQUEST = ( @@ -132,6 +143,268 @@ def setUp(self): binding_type=SAMLBindingTypes.POST, ) + def post_authn_request(self, application_slug: str = "test-app", relay_state="test_state"): + """Send an SP-initiated AuthnRequest using the HTTP-POST binding.""" + request = RequestProcessor( + self.source, self.request_factory.get("/"), relay_state + ).build_auth_n() + return self.client.post( + reverse( + "authentik_providers_saml:sso-post", + kwargs={"application_slug": application_slug}, + ), + { + "SAMLRequest": b64encode(request.encode()).decode(), + "RelayState": relay_state, + }, + ) + + def bind_excluded_consent_stage(self): + """Bind a consent stage to the authorization flow whose policy excludes every user + while the flow is planned.""" + binding = FlowStageBinding.objects.create( + target=self.provider.authorization_flow, + stage=ConsentStage.objects.create(name=generate_id()), + order=0, + evaluate_on_plan=True, + re_evaluate_policies=False, + ) + PolicyBinding.objects.create( + target=binding, + policy=DummyPolicy.objects.create( + name=generate_id(), result=False, wait_min=0, wait_max=1 + ), + order=0, + ) + + def executor_url(self, provider: SAMLProvider) -> str: + """Flow executor API URL for a provider's authorization flow.""" + return reverse( + "authentik_api:flow-executor", + kwargs={"flow_slug": provider.authorization_flow.slug}, + ) + + def assert_direct_post_response(self, response): + """Assert a direct SAML HTTP-POST response and its side effects.""" + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed(response, "if/saml_form_post.html") + self.assertEqual(response.context_data["redirect_uri"], self.provider.acs_url) + self.assertEqual(response.context_data["attrs"]["RelayState"], "test_state") + self.assertIn("SAMLResponse", response.context_data["attrs"]) + self.assertIn("no-store", response["Cache-Control"]) + self.assertEqual(response["Pragma"], "no-cache") + self.assertNotIn(SESSION_KEY_PLAN, self.client.session) + self.assertTrue(SAMLSession.objects.filter(provider=self.provider).exists()) + self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) + + def test_post_response_empty_flow_is_direct(self): + """An empty authorization flow returns the SAML POST form directly.""" + self.provider.sp_binding = SAMLBindings.POST + self.provider.save() + self.client.force_login(create_test_admin_user()) + + self.assert_direct_post_response(self.post_authn_request()) + + def test_post_response_empty_flow_error_is_error_page(self): + """A direct SAML error renders an HTML error without exposing internal details.""" + self.provider.sp_binding = SAMLBindings.POST + self.provider.save() + self.client.force_login(create_test_admin_user()) + + with patch.object( + AssertionProcessor, "build_response", side_effect=SAMLException("internal test error") + ): + response = self.post_authn_request() + + self.assertEqual(response.status_code, 400) + self.assertTemplateUsed(response, "if/error.html") + self.assertContains(response, "Failed to process SAML assertion.", status_code=400) + self.assertNotContains(response, "internal test error", status_code=400) + self.assertNotIn(SESSION_KEY_PLAN, self.client.session) + self.assertFalse(SAMLSession.objects.filter(provider=self.provider).exists()) + self.assertTrue(Event.objects.filter(action=EventAction.CONFIGURATION_ERROR).exists()) + + @patch_flag(ContinuousLogin, True) + def test_post_response_empty_flow_is_direct_with_continuous_login(self): + """Continuous login does not force an empty authorization flow into the executor.""" + self.provider.sp_binding = SAMLBindings.POST + self.provider.save() + self.client.force_login(create_test_admin_user()) + + self.assert_direct_post_response(self.post_authn_request()) + + @patch_flag(ContinuousLogin, True) + def test_redirect_response_empty_flow_is_direct_with_continuous_login(self): + """An empty authorization flow returns the SAML Redirect response directly.""" + self.provider.sp_binding = SAMLBindings.REDIRECT + self.provider.save() + app = Application.objects.get(slug="test-app") + params = RequestProcessor( + self.source, self.request_factory.get("/"), "test_state" + ).build_auth_n_detached() + self.client.force_login(create_test_admin_user()) + + response = self.client.get( + reverse( + "authentik_providers_saml:sso-redirect", + kwargs={"application_slug": app.slug}, + ), + params, + ) + + self.assertEqual(response.status_code, 302) + redirect = urlparse(response["Location"]) + self.assertEqual( + f"{redirect.scheme}://{redirect.netloc}{redirect.path}", self.provider.acs_url + ) + redirect_query = parse_qs(redirect.query) + self.assertEqual(redirect_query["RelayState"], ["test_state"]) + self.assertIn("SAMLResponse", redirect_query) + self.assertNotIn(SESSION_KEY_PLAN, self.client.session) + self.assertTrue(SAMLSession.objects.filter(provider=self.provider).exists()) + self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) + + def test_post_response_nonempty_flow_uses_executor(self): + """A configured authorization stage keeps using the flow executor.""" + self.provider.sp_binding = SAMLBindings.POST + self.provider.save() + FlowStageBinding.objects.create( + target=self.provider.authorization_flow, + stage=DummyStage.objects.create(name=generate_id()), + order=0, + ) + self.client.force_login(create_test_admin_user()) + + response = self.post_authn_request() + + self.assertEqual(response.status_code, 302) + self.assertEqual( + urlparse(response["Location"]).path, + reverse( + "authentik_core:if-flow", + kwargs={"flow_slug": self.provider.authorization_flow.slug}, + ), + ) + self.assertIn(SESSION_KEY_PLAN, self.client.session) + + def test_post_response_excluded_stage_is_direct(self): + """A configured stage that policies exclude for this user doesn't need the executor.""" + self.provider.sp_binding = SAMLBindings.POST + self.provider.save() + self.bind_excluded_consent_stage() + self.client.force_login(create_test_admin_user()) + + self.assert_direct_post_response(self.post_authn_request()) + + @patch_flag(ContinuousLogin, True) + def test_post_response_excluded_stage_uses_executor_with_continuous_login(self): + """With continuous login, a configured stage keeps the response in the flow executor + even when policies exclude it, since other tabs were told to wait for this flow.""" + self.provider.sp_binding = SAMLBindings.POST + self.provider.save() + self.bind_excluded_consent_stage() + self.client.force_login(create_test_admin_user()) + + response = self.post_authn_request() + + self.assertEqual(response.status_code, 302) + self.assertEqual( + urlparse(response["Location"]).path, + reverse( + "authentik_core:if-flow", + kwargs={"flow_slug": self.provider.authorization_flow.slug}, + ), + ) + self.assertFalse(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) + challenge = self.client.get(self.executor_url(self.provider)).json() + self.assertEqual(challenge["component"], "ak-stage-autosubmit") + self.assertEqual(challenge["url"], self.provider.acs_url) + + def test_post_to_executor_final_stage_does_not_reissue_assertion(self): + """A POST to the flow executor at the final stage keeps the challenge-response handling + instead of issuing another assertion.""" + self.provider.sp_binding = SAMLBindings.POST + self.provider.save() + FlowStageBinding.objects.create( + target=self.provider.authorization_flow, + stage=DummyStage.objects.create(name=generate_id()), + order=0, + ) + self.client.force_login(create_test_admin_user()) + self.post_authn_request() + executor_url = self.executor_url(self.provider) + self.client.get(executor_url) + self.client.post( + executor_url, {"component": "ak-stage-dummy"}, content_type="application/json" + ) + challenge = self.client.get(executor_url).json() + self.assertEqual(challenge["component"], "ak-stage-autosubmit") + authorize_events = Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION) + self.assertEqual(authorize_events.count(), 1) + + response = self.client.post( + executor_url, {"component": "ak-stage-autosubmit"}, content_type="application/json" + ) + + self.assertEqual(response.status_code, 400) + self.assertEqual(authorize_events.count(), 1) + self.assertEqual(SAMLSession.objects.filter(provider=self.provider).count(), 1) + + def test_direct_post_response_keeps_other_tab_plan(self): + """A direct SAML response in one tab leaves the flow another tab is running intact.""" + self.provider.sp_binding = SAMLBindings.POST + self.provider.save() + FlowStageBinding.objects.create( + target=self.provider.authorization_flow, + stage=DummyStage.objects.create(name=generate_id()), + order=0, + ) + direct_provider = SAMLProvider.objects.create( + name=generate_id(), + authorization_flow=create_test_flow(), + acs_url=self.provider.acs_url, + sp_binding=SAMLBindings.POST, + signing_kp=self.cert, + verification_kp=self.cert, + ) + direct_provider.property_mappings.set(SAMLPropertyMapping.objects.all()) + Application.objects.create(name="direct-app", slug="direct-app", provider=direct_provider) + self.client.force_login(create_test_admin_user()) + + # Tab A starts an authorization flow and stops at its first stage. + self.post_authn_request(relay_state="tab_a") + executor_url = self.executor_url(self.provider) + executor_query = {"query": "next=%2Ftab-a%2F"} + self.assertEqual( + self.client.get(executor_url, executor_query).json()["component"], "ak-stage-dummy" + ) + tab_a_plan = self.client.session[SESSION_KEY_PLAN] + tab_a_get = self.client.session[SESSION_KEY_GET] + + # Tab B signs into an application with an empty authorization flow. + response = self.post_authn_request("direct-app", relay_state="tab_b") + self.assertTemplateUsed(response, "if/saml_form_post.html") + self.assertEqual(response.context_data["attrs"]["RelayState"], "tab_b") + self.assertTrue(SAMLSession.objects.filter(provider=direct_provider).exists()) + self.assertEqual(self.client.session[SESSION_KEY_PLAN].flow_pk, tab_a_plan.flow_pk) + self.assertEqual( + self.client.session[SESSION_KEY_PLAN].context[PLAN_CONTEXT_APPLICATION].slug, + "test-app", + ) + self.assertEqual(self.client.session[SESSION_KEY_GET], tab_a_get) + + # Tab A finishes with its own request. + self.client.post( + executor_url, + {"component": "ak-stage-dummy"}, + content_type="application/json", + query_params=executor_query, + ) + challenge = self.client.get(executor_url, executor_query).json() + self.assertEqual(challenge["component"], "ak-stage-autosubmit") + self.assertEqual(challenge["url"], self.provider.acs_url) + self.assertEqual(challenge["attrs"]["RelayState"], "tab_a") + def test_signed_valid(self): """Test generated AuthNRequest with valid signature""" http_request = self.request_factory.get("/") @@ -183,6 +456,11 @@ def test_redirect_binding_continuous_login_final_redirect(self): continuous login, instead of an un-validated-serializer error.""" self.provider.sp_binding = SAMLBindings.REDIRECT self.provider.save() + FlowStageBinding.objects.create( + target=self.provider.authorization_flow, + stage=DummyStage.objects.create(name=generate_id()), + order=0, + ) app = Application.objects.get(slug="test-app") http_request = self.request_factory.get("/") params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() @@ -199,17 +477,25 @@ def test_redirect_binding_continuous_login_final_redirect(self): self.assertEqual(initiate.status_code, 302) # Drive the flow executor to completion, reaching SAMLFlowFinalView. - response = self.client.get( - reverse( - "authentik_api:flow-executor", - kwargs={"flow_slug": self.provider.authorization_flow.slug}, - ) + executor_url = reverse( + "authentik_api:flow-executor", + kwargs={"flow_slug": self.provider.authorization_flow.slug}, + ) + challenge = self.client.get(executor_url) + self.assertEqual(challenge.json()["component"], "ak-stage-dummy") + advance = self.client.post( + executor_url, + {"component": "ak-stage-dummy"}, + content_type="application/json", ) + self.assertEqual(advance.status_code, 302) + response = self.client.get(executor_url) self.assertEqual(response.status_code, 200) body = loads(response.content.decode()) self.assertEqual(body["component"], "xak-flow-redirect") self.assertTrue(body["final_redirect"]) + self.assertNotIn("continuous_login_hold", body) self.assertTrue(body["to"].startswith(self.provider.acs_url)) def test_request_encrypt(self): diff --git a/authentik/providers/saml/views/flows.py b/authentik/providers/saml/views/flows.py index 5ea2b332d08d..f279024f8cb2 100644 --- a/authentik/providers/saml/views/flows.py +++ b/authentik/providers/saml/views/flows.py @@ -4,6 +4,8 @@ from django.http import HttpRequest, HttpResponse from django.http.response import HttpResponseBadRequest from django.shortcuts import get_object_or_404, redirect +from django.template.response import TemplateResponse +from django.utils.cache import add_never_cache_headers from django.utils.http import urlencode from django.utils.translation import gettext as _ from structlog.stdlib import get_logger @@ -55,11 +57,24 @@ class SAMLFlowFinalView(ChallengeStageView): response_class = AutoSubmitChallengeResponse + def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: + """Fulfill direct authorization requests that arrive via the SAML HTTP-POST binding. + Requests to the flow executor keep the regular challenge-response handling.""" + if self.executor.direct_execution: + return self.get(request, *args, **kwargs) + return super().post(request, *args, **kwargs) + + def direct_error(self, message: str) -> HttpResponse: + """Render errors that bypass the flow interface as HTML.""" + return bad_request_message(self.request, message) + def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: application: Application = self.executor.plan.context[PLAN_CONTEXT_APPLICATION] provider: SAMLProvider = get_object_or_404(SAMLProvider, pk=application.provider_id) if PLAN_CONTEXT_SAML_AUTH_N_REQUEST not in self.executor.plan.context: self.logger.warning("No AuthNRequest in context") + if self.executor.direct_execution: + return self.direct_error(_("The SAML request payload is missing.")) return self.executor.stage_invalid() auth_n_request: AuthNRequest = self.executor.plan.context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] @@ -95,6 +110,8 @@ def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: message=f"Failed to process SAML assertion: {str(exc)}", provider=provider, ).from_http(self.request) + if self.executor.direct_execution: + return self.direct_error(_("Failed to process SAML assertion.")) return self.executor.stage_invalid() # Log Application Authorization @@ -111,6 +128,15 @@ def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: REQUEST_KEY_RELAY_STATE: auth_n_request.relay_state, } ) + if self.executor.direct_execution: + direct_response = TemplateResponse( + request, + "if/saml_form_post.html", + {"redirect_uri": provider.acs_url, "attrs": form_attrs}, + ) + add_never_cache_headers(direct_response) + direct_response["Pragma"] = "no-cache" + return direct_response return super().get( self.request, **{ @@ -138,7 +164,7 @@ def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: if auth_n_request.relay_state: url_args[REQUEST_KEY_RELAY_STATE] = auth_n_request.relay_state querystring = urlencode(url_args) - if ContinuousLogin.get(): + if ContinuousLogin.get() and not self.executor.direct_execution: return HttpChallengeResponse( RedirectChallenge( instance={ diff --git a/authentik/providers/saml/views/sso.py b/authentik/providers/saml/views/sso.py index ce73f8ee814a..e4e65f2460c7 100644 --- a/authentik/providers/saml/views/sso.py +++ b/authentik/providers/saml/views/sso.py @@ -14,7 +14,7 @@ from authentik.events.signals import get_login_event from authentik.flows.apps import ContinuousLogin from authentik.flows.exceptions import FlowNonApplicableException -from authentik.flows.models import in_memory_stage +from authentik.flows.models import FlowStageBinding, in_memory_stage from authentik.flows.planner import PLAN_CONTEXT_APPLICATION, PLAN_CONTEXT_SSO, FlowPlanner from authentik.flows.views.executor import SESSION_KEY_POST from authentik.lib.utils.errors import exception_to_dict @@ -57,6 +57,15 @@ def resolve_provider_application(self): SAMLProvider, pk=self.application.provider_id ) + def continuous_login_hold_required(self) -> bool: + """Conservatively hold tabs when authorization may require the flow executor. + + Stage policies can depend on the user who is about to authenticate, so they cannot be + evaluated accurately here. An entirely empty flow is the only flow known to be safe. + """ + # TODO: Revisit once #27280 lands, which holds tabs behind a single auto-redirecting source. + return FlowStageBinding.objects.filter(target=self.provider.authorization_flow).exists() + def check_saml_request(self) -> HttpRequest | None: """Handler to verify the SAML Request. Must be implemented by a subclass""" raise NotImplementedError @@ -129,7 +138,10 @@ def get(self, request: HttpRequest, application_slug: str) -> HttpResponse: next=self.get_resume_url(), allowed_silent_types=( [SAMLFlowFinalView] - if self.provider.sp_binding in [SAMLBindings.REDIRECT] and not ContinuousLogin.get() + if self.provider.sp_binding in [SAMLBindings.POST, SAMLBindings.REDIRECT] + # Under continuous login, other tabs hold whenever the authorization flow has + # bound stages, and only the flow interface tells them when this tab is done. + and (not ContinuousLogin.get() or not self.continuous_login_hold_required()) else [] ), ) diff --git a/packages/client-go/model_contextual_flow_info.go b/packages/client-go/model_contextual_flow_info.go index c714e17cba64..9761b911d089 100644 --- a/packages/client-go/model_contextual_flow_info.go +++ b/packages/client-go/model_contextual_flow_info.go @@ -27,6 +27,7 @@ type ContextualFlowInfo struct { CancelUrl string `json:"cancel_url"` Layout ContextualFlowInfoLayoutEnum `json:"layout"` Messages []FlowMessage `json:"messages,omitempty"` + ContinuousLoginHold *bool `json:"continuous_login_hold,omitempty"` AdditionalProperties map[string]interface{} } @@ -238,6 +239,38 @@ func (o *ContextualFlowInfo) SetMessages(v []FlowMessage) { o.Messages = v } +// GetContinuousLoginHold returns the ContinuousLoginHold field value if set, zero value otherwise. +func (o *ContextualFlowInfo) GetContinuousLoginHold() bool { + if o == nil || IsNil(o.ContinuousLoginHold) { + var ret bool + return ret + } + return *o.ContinuousLoginHold +} + +// GetContinuousLoginHoldOk returns a tuple with the ContinuousLoginHold field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ContextualFlowInfo) GetContinuousLoginHoldOk() (*bool, bool) { + if o == nil || IsNil(o.ContinuousLoginHold) { + return nil, false + } + return o.ContinuousLoginHold, true +} + +// HasContinuousLoginHold returns a boolean if a field has been set. +func (o *ContextualFlowInfo) HasContinuousLoginHold() bool { + if o != nil && !IsNil(o.ContinuousLoginHold) { + return true + } + + return false +} + +// SetContinuousLoginHold gets a reference to the given bool and assigns it to the ContinuousLoginHold field. +func (o *ContextualFlowInfo) SetContinuousLoginHold(v bool) { + o.ContinuousLoginHold = &v +} + func (o ContextualFlowInfo) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { @@ -262,6 +295,9 @@ func (o ContextualFlowInfo) ToMap() (map[string]interface{}, error) { if !IsNil(o.Messages) { toSerialize["messages"] = o.Messages } + if !IsNil(o.ContinuousLoginHold) { + toSerialize["continuous_login_hold"] = o.ContinuousLoginHold + } for key, value := range o.AdditionalProperties { toSerialize[key] = value @@ -312,6 +348,7 @@ func (o *ContextualFlowInfo) UnmarshalJSON(data []byte) (err error) { delete(additionalProperties, "cancel_url") delete(additionalProperties, "layout") delete(additionalProperties, "messages") + delete(additionalProperties, "continuous_login_hold") o.AdditionalProperties = additionalProperties } diff --git a/packages/client-go/model_redirect_challenge.go b/packages/client-go/model_redirect_challenge.go index 3d13e4773213..29162ba19005 100644 --- a/packages/client-go/model_redirect_challenge.go +++ b/packages/client-go/model_redirect_challenge.go @@ -26,6 +26,7 @@ type RedirectChallenge struct { ResponseErrors *map[string][]ErrorDetail `json:"response_errors,omitempty"` To string `json:"to"` FinalRedirect *bool `json:"final_redirect,omitempty"` + ContinuousLoginHold *bool `json:"continuous_login_hold,omitempty"` AdditionalProperties map[string]interface{} } @@ -209,6 +210,38 @@ func (o *RedirectChallenge) SetFinalRedirect(v bool) { o.FinalRedirect = &v } +// GetContinuousLoginHold returns the ContinuousLoginHold field value if set, zero value otherwise. +func (o *RedirectChallenge) GetContinuousLoginHold() bool { + if o == nil || IsNil(o.ContinuousLoginHold) { + var ret bool + return ret + } + return *o.ContinuousLoginHold +} + +// GetContinuousLoginHoldOk returns a tuple with the ContinuousLoginHold field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RedirectChallenge) GetContinuousLoginHoldOk() (*bool, bool) { + if o == nil || IsNil(o.ContinuousLoginHold) { + return nil, false + } + return o.ContinuousLoginHold, true +} + +// HasContinuousLoginHold returns a boolean if a field has been set. +func (o *RedirectChallenge) HasContinuousLoginHold() bool { + if o != nil && !IsNil(o.ContinuousLoginHold) { + return true + } + + return false +} + +// SetContinuousLoginHold gets a reference to the given bool and assigns it to the ContinuousLoginHold field. +func (o *RedirectChallenge) SetContinuousLoginHold(v bool) { + o.ContinuousLoginHold = &v +} + func (o RedirectChallenge) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { @@ -232,6 +265,9 @@ func (o RedirectChallenge) ToMap() (map[string]interface{}, error) { if !IsNil(o.FinalRedirect) { toSerialize["final_redirect"] = o.FinalRedirect } + if !IsNil(o.ContinuousLoginHold) { + toSerialize["continuous_login_hold"] = o.ContinuousLoginHold + } for key, value := range o.AdditionalProperties { toSerialize[key] = value @@ -280,6 +316,7 @@ func (o *RedirectChallenge) UnmarshalJSON(data []byte) (err error) { delete(additionalProperties, "response_errors") delete(additionalProperties, "to") delete(additionalProperties, "final_redirect") + delete(additionalProperties, "continuous_login_hold") o.AdditionalProperties = additionalProperties } diff --git a/packages/client-rust/src/models/contextual_flow_info.rs b/packages/client-rust/src/models/contextual_flow_info.rs index aa69b4b78f59..e1c5aa976521 100644 --- a/packages/client-rust/src/models/contextual_flow_info.rs +++ b/packages/client-rust/src/models/contextual_flow_info.rs @@ -30,6 +30,11 @@ pub struct ContextualFlowInfo { pub layout: models::ContextualFlowInfoLayoutEnum, #[serde(rename = "messages", skip_serializing_if = "Option::is_none")] pub messages: Option>, + #[serde( + rename = "continuous_login_hold", + skip_serializing_if = "Option::is_none" + )] + pub continuous_login_hold: Option, } impl ContextualFlowInfo { @@ -45,6 +50,7 @@ impl ContextualFlowInfo { cancel_url, layout, messages: None, + continuous_login_hold: None, } } } diff --git a/packages/client-rust/src/models/redirect_challenge.rs b/packages/client-rust/src/models/redirect_challenge.rs index e17d4c26feb8..ea35122abb3b 100644 --- a/packages/client-rust/src/models/redirect_challenge.rs +++ b/packages/client-rust/src/models/redirect_challenge.rs @@ -23,6 +23,11 @@ pub struct RedirectChallenge { pub to: String, #[serde(rename = "final_redirect", skip_serializing_if = "Option::is_none")] pub final_redirect: Option, + #[serde( + rename = "continuous_login_hold", + skip_serializing_if = "Option::is_none" + )] + pub continuous_login_hold: Option, } impl RedirectChallenge { @@ -34,6 +39,7 @@ impl RedirectChallenge { response_errors: None, to, final_redirect: None, + continuous_login_hold: None, } } } diff --git a/packages/client-ts/src/models/ContextualFlowInfo.ts b/packages/client-ts/src/models/ContextualFlowInfo.ts index 51c98bbe63c3..9658db35d816 100644 --- a/packages/client-ts/src/models/ContextualFlowInfo.ts +++ b/packages/client-ts/src/models/ContextualFlowInfo.ts @@ -33,6 +33,7 @@ export interface ContextualFlowInfo { cancelUrl: string; layout: ContextualFlowInfoLayoutEnum; messages?: Array; + continuousLoginHold?: boolean; } /** @@ -76,6 +77,8 @@ export function ContextualFlowInfoFromJSONTyped( json["messages"] == null ? undefined : (json["messages"] as Array).map(FlowMessageFromJSON), + continuousLoginHold: + json["continuous_login_hold"] == null ? undefined : json["continuous_login_hold"], }; } @@ -101,5 +104,6 @@ export function ContextualFlowInfoToJSONTyped( value["messages"] == null ? undefined : (value["messages"] as Array).map(FlowMessageToJSON), + continuous_login_hold: value["continuousLoginHold"], }; } diff --git a/packages/client-ts/src/models/RedirectChallenge.ts b/packages/client-ts/src/models/RedirectChallenge.ts index 4abf7d4384d8..874b9bcc7d77 100644 --- a/packages/client-ts/src/models/RedirectChallenge.ts +++ b/packages/client-ts/src/models/RedirectChallenge.ts @@ -26,6 +26,7 @@ export interface RedirectChallenge { responseErrors?: { [key: string]: Array }; to: string; finalRedirect?: boolean; + continuousLoginHold?: boolean; } /** @@ -54,6 +55,8 @@ export function RedirectChallengeFromJSONTyped( responseErrors: json["response_errors"] == null ? undefined : json["response_errors"], to: json["to"], finalRedirect: json["final_redirect"] == null ? undefined : json["final_redirect"], + continuousLoginHold: + json["continuous_login_hold"] == null ? undefined : json["continuous_login_hold"], }; } @@ -75,5 +78,6 @@ export function RedirectChallengeToJSONTyped( response_errors: value["responseErrors"], to: value["to"], final_redirect: value["finalRedirect"], + continuous_login_hold: value["continuousLoginHold"], }; } diff --git a/schema.yml b/schema.yml index e9dc220b4e3e..4da73914ea5f 100644 --- a/schema.yml +++ b/schema.yml @@ -39531,6 +39531,8 @@ components: type: array items: $ref: '#/components/schemas/FlowMessage' + continuous_login_hold: + type: boolean required: - cancel_url - layout @@ -57539,6 +57541,8 @@ components: final_redirect: type: boolean default: false + continuous_login_hold: + type: boolean required: - to RedirectChallengeResponseRequest: diff --git a/web/src/flow/controllers/FlowMultitabController.ts b/web/src/flow/controllers/FlowMultitabController.ts index 91c60cf41b90..3a5169d337a4 100644 --- a/web/src/flow/controllers/FlowMultitabController.ts +++ b/web/src/flow/controllers/FlowMultitabController.ts @@ -1,5 +1,6 @@ import type { Interface } from "#elements/Interface"; +import { continuousLoginExit } from "#flow/tabs/continuous-login"; import { AKMultiTabEvent } from "#flow/tabs/events"; import { multiTabOrchestrateLeave as dispatchTabExit, @@ -47,11 +48,13 @@ export class FlowMultitabController implements ReactiveController { if (next) { const url = new URL(next, window.location.origin); + const continuousLoginHold = challenge.flowInfo?.continuousLoginHold ?? true; + const exit = continuousLoginExit(url, window.location.origin, continuousLoginHold); - if (url.origin === window.location.origin) { - suppressNextExitForSameOriginNavigation(); - } else { + if (exit === "now") { dispatchTabExit(); + } else if (exit === "suppress") { + suppressNextExitForSameOriginNavigation(); } window.location.assign(url); diff --git a/web/src/flow/stages/RedirectStage.ts b/web/src/flow/stages/RedirectStage.ts index ddb2b5458238..a3cbc4b49878 100644 --- a/web/src/flow/stages/RedirectStage.ts +++ b/web/src/flow/stages/RedirectStage.ts @@ -8,7 +8,9 @@ import PFTitle from "@patternfly/patternfly/components/Title/title.css"; import { SlottedTemplateResult } from "#elements/types"; import { BaseStage } from "#flow/stages/base"; +import { continuousLoginExit } from "#flow/tabs/continuous-login"; import { + allowNextExitForSameOriginNavigation, multiTabOrchestrateLeave, multiTabOrchestrateResume, suppressNextExitForSameOriginNavigation, @@ -102,6 +104,7 @@ export class RedirectStage extends BaseStage { + it("reports a direct same-origin continuation on pagehide", () => { + expect( + continuousLoginExit(new URL("/application/saml/app/sso/", origin), origin, false), + ).toBe("on-pagehide"); + }); + + it("suppresses the exit for a same-origin continuation that may require authorization", () => { + expect( + continuousLoginExit(new URL("/application/saml/app/sso/", origin), origin, true), + ).toBe("suppress"); + }); + + it("reports an external continuation immediately", () => { + expect(continuousLoginExit(new URL("https://service.example/acs"), origin, true)).toBe( + "now", + ); + + expect(continuousLoginExit(new URL("https://service.example/acs"), origin, false)).toBe( + "now", + ); + }); +}); diff --git a/website/docs/releases/2026/v2026.11/index.mdx b/website/docs/releases/2026/v2026.11/index.mdx index 1dd3d828cc97..3e0d339ddcb0 100644 --- a/website/docs/releases/2026/v2026.11/index.mdx +++ b/website/docs/releases/2026/v2026.11/index.mdx @@ -321,6 +321,7 @@ User expiration rules schedule users for offboarding after a configured period o - **Token exchange**: An OAuth2 provider's JWT can be exchanged for a SAML response from a SAML provider that lists it under **Federated OAuth2/OpenID Providers**, for example to call AWS `AssumeRoleWithSAML`. Exchanged tokens keep the subject token's chain of `act` claims, up to 10 levels deep. - **SAML and WS-Federation providers**: Assertions can be encrypted with AES128-CBC, AES256-CBC, AES128-GCM, or AES256-GCM. New providers default to AES256-GCM, and existing providers keep AES128-CBC. Importing SP metadata selects the first algorithm in the SP's order of preference that authentik supports. For more details, including how to update existing providers, refer to [Encryption algorithm](../../../add-secure-apps/providers/saml/index.mdx#encryption-algorithm). - **SAML provider**: The new **Ignore ForceAuthn** option lets authentik reuse an existing session for SPs that always request re-authentication. For more details, refer to [Ignoring ForceAuthn](../../../add-secure-apps/providers/saml/index.mdx#ignoring-forceauthn). +- **SAML provider authorization**: When a provider's authorization flow has no stages, authentik sends the SAML response straight to the service provider, for both the Redirect and POST bindings, without showing the flow interface. With the POST binding, the browser shows a plain page that submits the response automatically. - **OpenID Connect sources**: Sources can be configured as public clients without a client secret when PKCE is enabled. - **Entra ID source**: Sources in national clouds, such as GCC High, DoD, and China, use the matching Microsoft Graph endpoint for scopes and group memberships, based on the **Profile URL**. For more details, refer to [Configure a source for a national cloud](../../../users-sources/sources/social-logins/entra-id/oauth/index.mdx#configure-a-source-for-a-national-cloud). - **LDAP source**: Synchronization deactivates users whose Active Directory `accountExpires` date has passed and ends their sessions.