authentik.enterprise.required_actions.tests.test_flows
Required action enforcement tests
1"""Required action enforcement tests""" 2 3from unittest.mock import PropertyMock, patch 4from urllib.parse import urlencode 5 6from django.core.cache import cache 7from django.core.mail.backends.locmem import EmailBackend 8from django.urls import reverse 9 10from authentik.core.models import User 11from authentik.core.tests.utils import create_test_admin_user, create_test_flow, create_test_user 12from authentik.enterprise.license import CACHE_KEY_ENTERPRISE_LICENSE 13from authentik.enterprise.required_actions import USER_ATTRIBUTE_REQUIRED_ACTIONS 14from authentik.enterprise.required_actions.flows import ( 15 RequiredActionCompleteStageView, 16 resolve_required_actions, 17) 18from authentik.enterprise.tests import enterprise_test, expiry_expired 19from authentik.events.models import Event, EventAction 20from authentik.events.utils import get_user 21from authentik.flows.markers import StageMarker 22from authentik.flows.models import ( 23 Flow, 24 FlowAuthenticationRequirement, 25 FlowDesignation, 26 FlowStageBinding, 27 in_memory_stage, 28) 29from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan 30from authentik.flows.tests import APIFlowTestCase 31from authentik.flows.views.executor import SESSION_KEY_PLAN, SESSION_KEY_POST 32from authentik.lib.generators import generate_id 33from authentik.policies.dummy.models import DummyPolicy 34from authentik.policies.models import PolicyBinding 35from authentik.stages.dummy.models import DummyStage 36from authentik.stages.email.models import EmailStage 37from authentik.stages.user_login.models import UserLoginStage 38 39 40def create_action_flow() -> Flow: 41 """Stage configuration flow with a single dummy stage, requiring authentication 42 like the built-in configuration flows""" 43 flow = create_test_flow( 44 FlowDesignation.STAGE_CONFIGURATION, 45 authentication=FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED, 46 ) 47 FlowStageBinding.objects.create( 48 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 49 ) 50 return flow 51 52 53def flow_url(flow: Flow) -> str: 54 return reverse("authentik_core:if-flow", kwargs={"flow_slug": flow.slug}) 55 56 57def executor_url(flow: Flow) -> str: 58 return reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 59 60 61class RequiredActionsTestCase(APIFlowTestCase): 62 def setUp(self): 63 super().setUp() 64 cache.delete(CACHE_KEY_ENTERPRISE_LICENSE) 65 self.user = create_test_user() 66 self.action = create_action_flow() 67 self.require([self.action.slug]) 68 69 def require(self, value): 70 self.user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS] = value 71 self.user.save() 72 73 def open_page(self, url: str): 74 return self.client.get(url, HTTP_ACCEPT="text/html") 75 76 def assertRedirectsToAction(self, url: str, action: Flow): 77 """Opening `url` sends the browser to `action`""" 78 response = self.open_page(url) 79 self.assertEqual(response.status_code, 302) 80 self.assertEqual(response.url, flow_url(action)) 81 82 def complete(self, action: Flow): 83 """Complete the dummy stage of `action` and return the completion response""" 84 self.assertStageResponse( 85 self.client.get(executor_url(action)), action, component="ak-stage-dummy" 86 ) 87 self.assertEqual(self.client.post(executor_url(action), {}).status_code, 302) 88 return self.client.get(executor_url(action)) 89 90 91class TestRequiredActions(RequiredActionsTestCase): 92 """Running required actions and resuming what the user was doing""" 93 94 def login(self, *stages: DummyStage, query: str = ""): 95 """Log in through an authentication flow with `stages` after the login stage""" 96 flow = create_test_flow(FlowDesignation.AUTHENTICATION) 97 bindings = [ 98 FlowStageBinding.objects.create( 99 target=flow, stage=UserLoginStage.objects.create(name=generate_id()), order=0 100 ) 101 ] 102 for order, stage in enumerate(stages, start=1): 103 bindings.append(FlowStageBinding.objects.create(target=flow, stage=stage, order=order)) 104 plan = FlowPlan( 105 flow_pk=flow.pk.hex, bindings=bindings, markers=[StageMarker()] * len(bindings) 106 ) 107 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 108 self.set_flow_plan(plan) 109 return flow, self.client.get(executor_url(flow), {"query": query}) 110 111 def test_resolve_preserves_order_in_one_query(self): 112 second = create_action_flow() 113 with self.assertNumQueries(1): 114 self.assertEqual( 115 resolve_required_actions([second.slug, self.action.slug, second.slug]), 116 [second, self.action, second], 117 ) 118 119 @enterprise_test() 120 def test_login_resumes_destination(self): 121 """After login, the action runs before the requested page, which is opened afterwards""" 122 self.login() 123 destination = reverse("authentik_providers_oauth2:authorize") 124 self.assertRedirectsToAction(destination, self.action) 125 self.assertStageRedirects(self.complete(self.action), destination) 126 127 self.user.refresh_from_db() 128 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 129 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 130 event = Event.objects.get(action=EventAction.REQUIRED_ACTION_COMPLETED) 131 self.assertEqual(event.context["flow_slug"], self.action.slug) 132 self.assertEqual(event.user, get_user(self.user)) 133 self.assertFalse( 134 Event.objects.filter( 135 action=EventAction.MODEL_UPDATED, context__model__model_name="user" 136 ).exists() 137 ) 138 139 @enterprise_test() 140 def test_existing_session_is_restricted(self): 141 """Actions added to a logged-in user apply to their next request""" 142 self.user.attributes.pop(USER_ATTRIBUTE_REQUIRED_ACTIONS) 143 self.user.save() 144 self.client.force_login(self.user) 145 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 146 self.require([self.action.slug]) 147 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 148 149 @enterprise_test() 150 def test_flow_in_progress_is_suspended(self): 151 """A flow that continues after login is paused for the action and then resumed""" 152 stage = DummyStage.objects.create(name=generate_id()) 153 query = urlencode({"next": reverse("authentik_core:if-user")}) 154 flow, response = self.login(stage, query=query) 155 self.assertEqual(response.status_code, 302) 156 157 response = self.client.get(executor_url(flow), {"query": query}) 158 self.assertStageRedirects(response, flow_url(self.action)) 159 self.assertStageRedirects(self.complete(self.action), f"{flow_url(flow)}?{query}") 160 161 response = self.client.get(executor_url(flow), {"query": query}) 162 self.assertStageResponse(response, flow, component="ak-stage-dummy") 163 response = self.client.post(f"{executor_url(flow)}?{urlencode({'query': query})}", {}) 164 self.assertStageRedirects(response, reverse("authentik_core:if-user")) 165 166 @enterprise_test() 167 def test_navigation_keeps_progress(self): 168 """Opening another page during an action returns to it without restarting""" 169 self.client.force_login(self.user) 170 destination = reverse("authentik_core:if-user") 171 self.assertRedirectsToAction(destination, self.action) 172 self.client.get(executor_url(self.action)) 173 plan = self.get_flow_plan() 174 self.assertRedirectsToAction(reverse("authentik_core:if-admin"), self.action) 175 self.assertEqual(self.get_flow_plan().bindings, plan.bindings) 176 self.assertStageRedirects(self.complete(self.action), destination) 177 178 @enterprise_test() 179 def test_direct_entry_completes(self): 180 """Opening the action directly still records it as complete""" 181 self.client.force_login(self.user) 182 self.assertStageRedirects( 183 self.complete(self.action), reverse("authentik_core:root-redirect") 184 ) 185 self.user.refresh_from_db() 186 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 187 188 @enterprise_test() 189 def test_multiple_actions_run_in_order(self): 190 second = create_action_flow() 191 self.require([self.action.slug, second.slug]) 192 self.client.force_login(self.user) 193 destination = reverse("authentik_core:if-user") 194 195 self.assertRedirectsToAction(destination, self.action) 196 self.assertStageRedirects(self.complete(self.action), destination) 197 self.user.refresh_from_db() 198 self.assertEqual(self.user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS], [second.slug]) 199 200 self.assertRedirectsToAction(destination, second) 201 self.assertStageRedirects(self.complete(second), destination) 202 self.user.refresh_from_db() 203 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 204 205 @enterprise_test() 206 def test_single_slug(self): 207 """A single flow slug works without being wrapped in a list""" 208 self.require(self.action.slug) 209 self.client.force_login(self.user) 210 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 211 self.complete(self.action) 212 self.user.refresh_from_db() 213 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 214 215 @enterprise_test() 216 def test_replaced_action_keeps_destination(self): 217 """Replacing an action in progress still returns the user to their page afterwards""" 218 self.client.force_login(self.user) 219 destination = reverse("authentik_core:if-user") 220 self.assertRedirectsToAction(destination, self.action) 221 replacement = create_action_flow() 222 self.require([replacement.slug]) 223 response = self.client.get(executor_url(self.action)) 224 self.assertStageRedirects(response, flow_url(replacement)) 225 self.assertStageRedirects(self.complete(replacement), destination) 226 227 @enterprise_test() 228 def test_post_is_resumed_with_its_body(self): 229 """A POST is opened again with GET afterwards, so its body is kept like on login""" 230 self.client.force_login(self.user) 231 destination = reverse("authentik_core:if-user") 232 response = self.client.post( 233 destination, 234 urlencode({"SAMLRequest": "request"}), 235 content_type="application/x-www-form-urlencoded", 236 HTTP_ACCEPT="text/html", 237 ) 238 self.assertEqual(response.status_code, 302) 239 self.assertEqual(response.url, flow_url(self.action)) 240 self.assertEqual(self.client.session[SESSION_KEY_POST]["SAMLRequest"], "request") 241 self.assertStageRedirects(self.complete(self.action), destination) 242 243 @enterprise_test() 244 def test_flow_post_body_is_not_kept(self): 245 """Suspending a flow doesn't copy the submitted form, such as a password, into the 246 session""" 247 flow, _ = self.login(DummyStage.objects.create(name=generate_id())) 248 response = self.client.post( 249 executor_url(flow), 250 urlencode({"password": generate_id()}), 251 content_type="application/x-www-form-urlencoded", 252 ) 253 self.assertStageRedirects(response, flow_url(self.action)) 254 self.assertNotIn(SESSION_KEY_POST, self.client.session) 255 256 @enterprise_test() 257 def test_completion_applies_to_planned_user(self): 258 """An action plan restored in another browser, as from an email link, completes for 259 the user it was planned for""" 260 plan = FlowPlan(flow_pk=self.action.pk.hex) 261 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 262 plan.append_stage( 263 in_memory_stage( 264 RequiredActionCompleteStageView, 265 flow_slug=self.action.slug, 266 resume_url=reverse("authentik_core:root-redirect"), 267 resume_plan=None, 268 ) 269 ) 270 self.set_flow_plan(plan) 271 response = self.client.get(executor_url(self.action)) 272 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 273 self.user.refresh_from_db() 274 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 275 276 @enterprise_test() 277 @patch( 278 "authentik.stages.email.models.EmailStage.backend_class", 279 PropertyMock(return_value=EmailBackend), 280 ) 281 def test_action_plan_has_pending_user(self): 282 action = create_test_flow( 283 FlowDesignation.STAGE_CONFIGURATION, 284 authentication=FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED, 285 ) 286 FlowStageBinding.objects.create( 287 target=action, stage=EmailStage.objects.create(name=generate_id()), order=0 288 ) 289 self.require([action.slug]) 290 self.client.force_login(self.user) 291 self.assertRedirectsToAction(reverse("authentik_core:if-user"), action) 292 self.assertStageResponse( 293 self.client.get(executor_url(action)), action, component="ak-stage-email" 294 ) 295 296 @enterprise_test() 297 def test_completion_preserves_concurrent_updates(self): 298 """An update to the user while the action runs survives its completion""" 299 self.client.force_login(self.user) 300 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 301 dispatch = RequiredActionCompleteStageView.dispatch 302 303 def update_then_complete(view, request): 304 user = User.objects.get(pk=self.user.pk) 305 user.attributes["updated"] = "preserved" 306 user.save(update_fields=["attributes"]) 307 return dispatch(view, request) 308 309 with patch.object(RequiredActionCompleteStageView, "dispatch", update_then_complete): 310 self.complete(self.action) 311 self.user.refresh_from_db() 312 self.assertEqual(self.user.attributes["updated"], "preserved") 313 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 314 315 @enterprise_test() 316 def test_invalid_actions_fail_closed(self): 317 """An action that cannot run keeps the session restricted""" 318 denied = create_action_flow() 319 PolicyBinding.objects.create( 320 policy=DummyPolicy.objects.create( 321 name=generate_id(), result=False, wait_min=0, wait_max=1 322 ), 323 target=denied, 324 order=0, 325 ) 326 self.client.force_login(self.user) 327 for value in (["does-not-exist"], [denied.slug], [42], None, False, 0, "", {}): 328 with self.subTest(value=value): 329 self.require(value) 330 response = self.open_page(reverse("authentik_core:if-user")) 331 self.assertEqual(response.status_code, 403) 332 333 @enterprise_test(expiry=expiry_expired) 334 def test_expired_license_still_enforces(self): 335 self.client.force_login(self.user) 336 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 337 338 def test_unlicensed_ignores_actions(self): 339 self.client.force_login(self.user) 340 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 341 342 343class TestRequiredActionsMiddleware(RequiredActionsTestCase): 344 """What a session with required actions can and cannot reach""" 345 346 def setUp(self): 347 super().setUp() 348 self.client.force_login(self.user) 349 350 @enterprise_test() 351 def test_api_denied(self): 352 for route in ("authentik_api:application-list", "authentik_api:flow-list"): 353 with self.subTest(route=route): 354 response = self.client.get(reverse(route), HTTP_ACCEPT="application/json") 355 self.assertEqual(response.status_code, 403) 356 357 @enterprise_test() 358 def test_user_cannot_remove_own_actions(self): 359 """Permission to edit themselves doesn't let a user skip their actions""" 360 self.user.assign_perms_to_managed_role("authentik_core.view_user") 361 self.user.assign_perms_to_managed_role("authentik_core.change_user", self.user) 362 response = self.client.patch( 363 reverse("authentik_api:user-detail", kwargs={"pk": self.user.pk}), 364 {"attributes": {}}, 365 format="json", 366 ) 367 self.assertEqual(response.status_code, 403) 368 self.user.refresh_from_db() 369 self.assertEqual(self.user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS], [self.action.slug]) 370 371 @enterprise_test() 372 def test_flow_interface_reads_allowed(self): 373 """The flow interface can load its configuration and user while the API is denied""" 374 self.assertEqual(self.client.get(reverse("authentik_api:brand-list")).status_code, 403) 375 for route in ("authentik_api:user-me", "authentik_api:config"): 376 with self.subTest(route=route): 377 self.assertEqual(self.client.get(reverse(route)).status_code, 200) 378 379 @enterprise_test() 380 def test_other_flow_redirected_to_action(self): 381 other = create_test_flow(FlowDesignation.STAGE_CONFIGURATION) 382 self.assertRedirectsToAction(flow_url(other), self.action) 383 384 @enterprise_test() 385 def test_logout_allowed(self): 386 Flow.objects.filter(designation=FlowDesignation.INVALIDATION).delete() 387 invalidation = create_test_flow(FlowDesignation.INVALIDATION) 388 response = self.client.get(reverse("authentik_flows:default-invalidation")) 389 self.assertEqual(response.status_code, 302) 390 self.assertEqual(response.url, flow_url(invalidation)) 391 self.assertEqual(self.open_page(flow_url(invalidation)).status_code, 200) 392 393 @enterprise_test() 394 def test_impersonation_not_restricted(self): 395 """An administrator impersonating the user isn't sent through their actions""" 396 self.client.force_login(create_test_admin_user()) 397 response = self.client.post( 398 reverse("authentik_api:user-impersonate", kwargs={"pk": self.user.pk}), 399 data={"reason": generate_id()}, 400 ) 401 self.assertEqual(response.status_code, 204) 402 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 403 self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
41def create_action_flow() -> Flow: 42 """Stage configuration flow with a single dummy stage, requiring authentication 43 like the built-in configuration flows""" 44 flow = create_test_flow( 45 FlowDesignation.STAGE_CONFIGURATION, 46 authentication=FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED, 47 ) 48 FlowStageBinding.objects.create( 49 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 50 ) 51 return flow
Stage configuration flow with a single dummy stage, requiring authentication like the built-in configuration flows
62class RequiredActionsTestCase(APIFlowTestCase): 63 def setUp(self): 64 super().setUp() 65 cache.delete(CACHE_KEY_ENTERPRISE_LICENSE) 66 self.user = create_test_user() 67 self.action = create_action_flow() 68 self.require([self.action.slug]) 69 70 def require(self, value): 71 self.user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS] = value 72 self.user.save() 73 74 def open_page(self, url: str): 75 return self.client.get(url, HTTP_ACCEPT="text/html") 76 77 def assertRedirectsToAction(self, url: str, action: Flow): 78 """Opening `url` sends the browser to `action`""" 79 response = self.open_page(url) 80 self.assertEqual(response.status_code, 302) 81 self.assertEqual(response.url, flow_url(action)) 82 83 def complete(self, action: Flow): 84 """Complete the dummy stage of `action` and return the completion response""" 85 self.assertStageResponse( 86 self.client.get(executor_url(action)), action, component="ak-stage-dummy" 87 ) 88 self.assertEqual(self.client.post(executor_url(action), {}).status_code, 302) 89 return self.client.get(executor_url(action))
Flow test case with a DRF client
63 def setUp(self): 64 super().setUp() 65 cache.delete(CACHE_KEY_ENTERPRISE_LICENSE) 66 self.user = create_test_user() 67 self.action = create_action_flow() 68 self.require([self.action.slug])
Hook method for setting up the test fixture before exercising it.
77 def assertRedirectsToAction(self, url: str, action: Flow): 78 """Opening `url` sends the browser to `action`""" 79 response = self.open_page(url) 80 self.assertEqual(response.status_code, 302) 81 self.assertEqual(response.url, flow_url(action))
Opening url sends the browser to action
83 def complete(self, action: Flow): 84 """Complete the dummy stage of `action` and return the completion response""" 85 self.assertStageResponse( 86 self.client.get(executor_url(action)), action, component="ak-stage-dummy" 87 ) 88 self.assertEqual(self.client.post(executor_url(action), {}).status_code, 302) 89 return self.client.get(executor_url(action))
Complete the dummy stage of action and return the completion response
92class TestRequiredActions(RequiredActionsTestCase): 93 """Running required actions and resuming what the user was doing""" 94 95 def login(self, *stages: DummyStage, query: str = ""): 96 """Log in through an authentication flow with `stages` after the login stage""" 97 flow = create_test_flow(FlowDesignation.AUTHENTICATION) 98 bindings = [ 99 FlowStageBinding.objects.create( 100 target=flow, stage=UserLoginStage.objects.create(name=generate_id()), order=0 101 ) 102 ] 103 for order, stage in enumerate(stages, start=1): 104 bindings.append(FlowStageBinding.objects.create(target=flow, stage=stage, order=order)) 105 plan = FlowPlan( 106 flow_pk=flow.pk.hex, bindings=bindings, markers=[StageMarker()] * len(bindings) 107 ) 108 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 109 self.set_flow_plan(plan) 110 return flow, self.client.get(executor_url(flow), {"query": query}) 111 112 def test_resolve_preserves_order_in_one_query(self): 113 second = create_action_flow() 114 with self.assertNumQueries(1): 115 self.assertEqual( 116 resolve_required_actions([second.slug, self.action.slug, second.slug]), 117 [second, self.action, second], 118 ) 119 120 @enterprise_test() 121 def test_login_resumes_destination(self): 122 """After login, the action runs before the requested page, which is opened afterwards""" 123 self.login() 124 destination = reverse("authentik_providers_oauth2:authorize") 125 self.assertRedirectsToAction(destination, self.action) 126 self.assertStageRedirects(self.complete(self.action), destination) 127 128 self.user.refresh_from_db() 129 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 130 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 131 event = Event.objects.get(action=EventAction.REQUIRED_ACTION_COMPLETED) 132 self.assertEqual(event.context["flow_slug"], self.action.slug) 133 self.assertEqual(event.user, get_user(self.user)) 134 self.assertFalse( 135 Event.objects.filter( 136 action=EventAction.MODEL_UPDATED, context__model__model_name="user" 137 ).exists() 138 ) 139 140 @enterprise_test() 141 def test_existing_session_is_restricted(self): 142 """Actions added to a logged-in user apply to their next request""" 143 self.user.attributes.pop(USER_ATTRIBUTE_REQUIRED_ACTIONS) 144 self.user.save() 145 self.client.force_login(self.user) 146 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 147 self.require([self.action.slug]) 148 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 149 150 @enterprise_test() 151 def test_flow_in_progress_is_suspended(self): 152 """A flow that continues after login is paused for the action and then resumed""" 153 stage = DummyStage.objects.create(name=generate_id()) 154 query = urlencode({"next": reverse("authentik_core:if-user")}) 155 flow, response = self.login(stage, query=query) 156 self.assertEqual(response.status_code, 302) 157 158 response = self.client.get(executor_url(flow), {"query": query}) 159 self.assertStageRedirects(response, flow_url(self.action)) 160 self.assertStageRedirects(self.complete(self.action), f"{flow_url(flow)}?{query}") 161 162 response = self.client.get(executor_url(flow), {"query": query}) 163 self.assertStageResponse(response, flow, component="ak-stage-dummy") 164 response = self.client.post(f"{executor_url(flow)}?{urlencode({'query': query})}", {}) 165 self.assertStageRedirects(response, reverse("authentik_core:if-user")) 166 167 @enterprise_test() 168 def test_navigation_keeps_progress(self): 169 """Opening another page during an action returns to it without restarting""" 170 self.client.force_login(self.user) 171 destination = reverse("authentik_core:if-user") 172 self.assertRedirectsToAction(destination, self.action) 173 self.client.get(executor_url(self.action)) 174 plan = self.get_flow_plan() 175 self.assertRedirectsToAction(reverse("authentik_core:if-admin"), self.action) 176 self.assertEqual(self.get_flow_plan().bindings, plan.bindings) 177 self.assertStageRedirects(self.complete(self.action), destination) 178 179 @enterprise_test() 180 def test_direct_entry_completes(self): 181 """Opening the action directly still records it as complete""" 182 self.client.force_login(self.user) 183 self.assertStageRedirects( 184 self.complete(self.action), reverse("authentik_core:root-redirect") 185 ) 186 self.user.refresh_from_db() 187 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 188 189 @enterprise_test() 190 def test_multiple_actions_run_in_order(self): 191 second = create_action_flow() 192 self.require([self.action.slug, second.slug]) 193 self.client.force_login(self.user) 194 destination = reverse("authentik_core:if-user") 195 196 self.assertRedirectsToAction(destination, self.action) 197 self.assertStageRedirects(self.complete(self.action), destination) 198 self.user.refresh_from_db() 199 self.assertEqual(self.user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS], [second.slug]) 200 201 self.assertRedirectsToAction(destination, second) 202 self.assertStageRedirects(self.complete(second), destination) 203 self.user.refresh_from_db() 204 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 205 206 @enterprise_test() 207 def test_single_slug(self): 208 """A single flow slug works without being wrapped in a list""" 209 self.require(self.action.slug) 210 self.client.force_login(self.user) 211 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 212 self.complete(self.action) 213 self.user.refresh_from_db() 214 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 215 216 @enterprise_test() 217 def test_replaced_action_keeps_destination(self): 218 """Replacing an action in progress still returns the user to their page afterwards""" 219 self.client.force_login(self.user) 220 destination = reverse("authentik_core:if-user") 221 self.assertRedirectsToAction(destination, self.action) 222 replacement = create_action_flow() 223 self.require([replacement.slug]) 224 response = self.client.get(executor_url(self.action)) 225 self.assertStageRedirects(response, flow_url(replacement)) 226 self.assertStageRedirects(self.complete(replacement), destination) 227 228 @enterprise_test() 229 def test_post_is_resumed_with_its_body(self): 230 """A POST is opened again with GET afterwards, so its body is kept like on login""" 231 self.client.force_login(self.user) 232 destination = reverse("authentik_core:if-user") 233 response = self.client.post( 234 destination, 235 urlencode({"SAMLRequest": "request"}), 236 content_type="application/x-www-form-urlencoded", 237 HTTP_ACCEPT="text/html", 238 ) 239 self.assertEqual(response.status_code, 302) 240 self.assertEqual(response.url, flow_url(self.action)) 241 self.assertEqual(self.client.session[SESSION_KEY_POST]["SAMLRequest"], "request") 242 self.assertStageRedirects(self.complete(self.action), destination) 243 244 @enterprise_test() 245 def test_flow_post_body_is_not_kept(self): 246 """Suspending a flow doesn't copy the submitted form, such as a password, into the 247 session""" 248 flow, _ = self.login(DummyStage.objects.create(name=generate_id())) 249 response = self.client.post( 250 executor_url(flow), 251 urlencode({"password": generate_id()}), 252 content_type="application/x-www-form-urlencoded", 253 ) 254 self.assertStageRedirects(response, flow_url(self.action)) 255 self.assertNotIn(SESSION_KEY_POST, self.client.session) 256 257 @enterprise_test() 258 def test_completion_applies_to_planned_user(self): 259 """An action plan restored in another browser, as from an email link, completes for 260 the user it was planned for""" 261 plan = FlowPlan(flow_pk=self.action.pk.hex) 262 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 263 plan.append_stage( 264 in_memory_stage( 265 RequiredActionCompleteStageView, 266 flow_slug=self.action.slug, 267 resume_url=reverse("authentik_core:root-redirect"), 268 resume_plan=None, 269 ) 270 ) 271 self.set_flow_plan(plan) 272 response = self.client.get(executor_url(self.action)) 273 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 274 self.user.refresh_from_db() 275 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 276 277 @enterprise_test() 278 @patch( 279 "authentik.stages.email.models.EmailStage.backend_class", 280 PropertyMock(return_value=EmailBackend), 281 ) 282 def test_action_plan_has_pending_user(self): 283 action = create_test_flow( 284 FlowDesignation.STAGE_CONFIGURATION, 285 authentication=FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED, 286 ) 287 FlowStageBinding.objects.create( 288 target=action, stage=EmailStage.objects.create(name=generate_id()), order=0 289 ) 290 self.require([action.slug]) 291 self.client.force_login(self.user) 292 self.assertRedirectsToAction(reverse("authentik_core:if-user"), action) 293 self.assertStageResponse( 294 self.client.get(executor_url(action)), action, component="ak-stage-email" 295 ) 296 297 @enterprise_test() 298 def test_completion_preserves_concurrent_updates(self): 299 """An update to the user while the action runs survives its completion""" 300 self.client.force_login(self.user) 301 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 302 dispatch = RequiredActionCompleteStageView.dispatch 303 304 def update_then_complete(view, request): 305 user = User.objects.get(pk=self.user.pk) 306 user.attributes["updated"] = "preserved" 307 user.save(update_fields=["attributes"]) 308 return dispatch(view, request) 309 310 with patch.object(RequiredActionCompleteStageView, "dispatch", update_then_complete): 311 self.complete(self.action) 312 self.user.refresh_from_db() 313 self.assertEqual(self.user.attributes["updated"], "preserved") 314 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 315 316 @enterprise_test() 317 def test_invalid_actions_fail_closed(self): 318 """An action that cannot run keeps the session restricted""" 319 denied = create_action_flow() 320 PolicyBinding.objects.create( 321 policy=DummyPolicy.objects.create( 322 name=generate_id(), result=False, wait_min=0, wait_max=1 323 ), 324 target=denied, 325 order=0, 326 ) 327 self.client.force_login(self.user) 328 for value in (["does-not-exist"], [denied.slug], [42], None, False, 0, "", {}): 329 with self.subTest(value=value): 330 self.require(value) 331 response = self.open_page(reverse("authentik_core:if-user")) 332 self.assertEqual(response.status_code, 403) 333 334 @enterprise_test(expiry=expiry_expired) 335 def test_expired_license_still_enforces(self): 336 self.client.force_login(self.user) 337 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 338 339 def test_unlicensed_ignores_actions(self): 340 self.client.force_login(self.user) 341 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200)
Running required actions and resuming what the user was doing
95 def login(self, *stages: DummyStage, query: str = ""): 96 """Log in through an authentication flow with `stages` after the login stage""" 97 flow = create_test_flow(FlowDesignation.AUTHENTICATION) 98 bindings = [ 99 FlowStageBinding.objects.create( 100 target=flow, stage=UserLoginStage.objects.create(name=generate_id()), order=0 101 ) 102 ] 103 for order, stage in enumerate(stages, start=1): 104 bindings.append(FlowStageBinding.objects.create(target=flow, stage=stage, order=order)) 105 plan = FlowPlan( 106 flow_pk=flow.pk.hex, bindings=bindings, markers=[StageMarker()] * len(bindings) 107 ) 108 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 109 self.set_flow_plan(plan) 110 return flow, self.client.get(executor_url(flow), {"query": query})
Log in through an authentication flow with stages after the login stage
120 @enterprise_test() 121 def test_login_resumes_destination(self): 122 """After login, the action runs before the requested page, which is opened afterwards""" 123 self.login() 124 destination = reverse("authentik_providers_oauth2:authorize") 125 self.assertRedirectsToAction(destination, self.action) 126 self.assertStageRedirects(self.complete(self.action), destination) 127 128 self.user.refresh_from_db() 129 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes) 130 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 131 event = Event.objects.get(action=EventAction.REQUIRED_ACTION_COMPLETED) 132 self.assertEqual(event.context["flow_slug"], self.action.slug) 133 self.assertEqual(event.user, get_user(self.user)) 134 self.assertFalse( 135 Event.objects.filter( 136 action=EventAction.MODEL_UPDATED, context__model__model_name="user" 137 ).exists() 138 )
After login, the action runs before the requested page, which is opened afterwards
140 @enterprise_test() 141 def test_existing_session_is_restricted(self): 142 """Actions added to a logged-in user apply to their next request""" 143 self.user.attributes.pop(USER_ATTRIBUTE_REQUIRED_ACTIONS) 144 self.user.save() 145 self.client.force_login(self.user) 146 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 147 self.require([self.action.slug]) 148 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action)
Actions added to a logged-in user apply to their next request
150 @enterprise_test() 151 def test_flow_in_progress_is_suspended(self): 152 """A flow that continues after login is paused for the action and then resumed""" 153 stage = DummyStage.objects.create(name=generate_id()) 154 query = urlencode({"next": reverse("authentik_core:if-user")}) 155 flow, response = self.login(stage, query=query) 156 self.assertEqual(response.status_code, 302) 157 158 response = self.client.get(executor_url(flow), {"query": query}) 159 self.assertStageRedirects(response, flow_url(self.action)) 160 self.assertStageRedirects(self.complete(self.action), f"{flow_url(flow)}?{query}") 161 162 response = self.client.get(executor_url(flow), {"query": query}) 163 self.assertStageResponse(response, flow, component="ak-stage-dummy") 164 response = self.client.post(f"{executor_url(flow)}?{urlencode({'query': query})}", {}) 165 self.assertStageRedirects(response, reverse("authentik_core:if-user"))
A flow that continues after login is paused for the action and then resumed
179 @enterprise_test() 180 def test_direct_entry_completes(self): 181 """Opening the action directly still records it as complete""" 182 self.client.force_login(self.user) 183 self.assertStageRedirects( 184 self.complete(self.action), reverse("authentik_core:root-redirect") 185 ) 186 self.user.refresh_from_db() 187 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes)
Opening the action directly still records it as complete
189 @enterprise_test() 190 def test_multiple_actions_run_in_order(self): 191 second = create_action_flow() 192 self.require([self.action.slug, second.slug]) 193 self.client.force_login(self.user) 194 destination = reverse("authentik_core:if-user") 195 196 self.assertRedirectsToAction(destination, self.action) 197 self.assertStageRedirects(self.complete(self.action), destination) 198 self.user.refresh_from_db() 199 self.assertEqual(self.user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS], [second.slug]) 200 201 self.assertRedirectsToAction(destination, second) 202 self.assertStageRedirects(self.complete(second), destination) 203 self.user.refresh_from_db() 204 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes)
206 @enterprise_test() 207 def test_single_slug(self): 208 """A single flow slug works without being wrapped in a list""" 209 self.require(self.action.slug) 210 self.client.force_login(self.user) 211 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 212 self.complete(self.action) 213 self.user.refresh_from_db() 214 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes)
A single flow slug works without being wrapped in a list
216 @enterprise_test() 217 def test_replaced_action_keeps_destination(self): 218 """Replacing an action in progress still returns the user to their page afterwards""" 219 self.client.force_login(self.user) 220 destination = reverse("authentik_core:if-user") 221 self.assertRedirectsToAction(destination, self.action) 222 replacement = create_action_flow() 223 self.require([replacement.slug]) 224 response = self.client.get(executor_url(self.action)) 225 self.assertStageRedirects(response, flow_url(replacement)) 226 self.assertStageRedirects(self.complete(replacement), destination)
Replacing an action in progress still returns the user to their page afterwards
228 @enterprise_test() 229 def test_post_is_resumed_with_its_body(self): 230 """A POST is opened again with GET afterwards, so its body is kept like on login""" 231 self.client.force_login(self.user) 232 destination = reverse("authentik_core:if-user") 233 response = self.client.post( 234 destination, 235 urlencode({"SAMLRequest": "request"}), 236 content_type="application/x-www-form-urlencoded", 237 HTTP_ACCEPT="text/html", 238 ) 239 self.assertEqual(response.status_code, 302) 240 self.assertEqual(response.url, flow_url(self.action)) 241 self.assertEqual(self.client.session[SESSION_KEY_POST]["SAMLRequest"], "request") 242 self.assertStageRedirects(self.complete(self.action), destination)
A POST is opened again with GET afterwards, so its body is kept like on login
244 @enterprise_test() 245 def test_flow_post_body_is_not_kept(self): 246 """Suspending a flow doesn't copy the submitted form, such as a password, into the 247 session""" 248 flow, _ = self.login(DummyStage.objects.create(name=generate_id())) 249 response = self.client.post( 250 executor_url(flow), 251 urlencode({"password": generate_id()}), 252 content_type="application/x-www-form-urlencoded", 253 ) 254 self.assertStageRedirects(response, flow_url(self.action)) 255 self.assertNotIn(SESSION_KEY_POST, self.client.session)
Suspending a flow doesn't copy the submitted form, such as a password, into the session
257 @enterprise_test() 258 def test_completion_applies_to_planned_user(self): 259 """An action plan restored in another browser, as from an email link, completes for 260 the user it was planned for""" 261 plan = FlowPlan(flow_pk=self.action.pk.hex) 262 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 263 plan.append_stage( 264 in_memory_stage( 265 RequiredActionCompleteStageView, 266 flow_slug=self.action.slug, 267 resume_url=reverse("authentik_core:root-redirect"), 268 resume_plan=None, 269 ) 270 ) 271 self.set_flow_plan(plan) 272 response = self.client.get(executor_url(self.action)) 273 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 274 self.user.refresh_from_db() 275 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes)
An action plan restored in another browser, as from an email link, completes for the user it was planned for
277 @enterprise_test() 278 @patch( 279 "authentik.stages.email.models.EmailStage.backend_class", 280 PropertyMock(return_value=EmailBackend), 281 ) 282 def test_action_plan_has_pending_user(self): 283 action = create_test_flow( 284 FlowDesignation.STAGE_CONFIGURATION, 285 authentication=FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED, 286 ) 287 FlowStageBinding.objects.create( 288 target=action, stage=EmailStage.objects.create(name=generate_id()), order=0 289 ) 290 self.require([action.slug]) 291 self.client.force_login(self.user) 292 self.assertRedirectsToAction(reverse("authentik_core:if-user"), action) 293 self.assertStageResponse( 294 self.client.get(executor_url(action)), action, component="ak-stage-email" 295 )
297 @enterprise_test() 298 def test_completion_preserves_concurrent_updates(self): 299 """An update to the user while the action runs survives its completion""" 300 self.client.force_login(self.user) 301 self.assertRedirectsToAction(reverse("authentik_core:if-user"), self.action) 302 dispatch = RequiredActionCompleteStageView.dispatch 303 304 def update_then_complete(view, request): 305 user = User.objects.get(pk=self.user.pk) 306 user.attributes["updated"] = "preserved" 307 user.save(update_fields=["attributes"]) 308 return dispatch(view, request) 309 310 with patch.object(RequiredActionCompleteStageView, "dispatch", update_then_complete): 311 self.complete(self.action) 312 self.user.refresh_from_db() 313 self.assertEqual(self.user.attributes["updated"], "preserved") 314 self.assertNotIn(USER_ATTRIBUTE_REQUIRED_ACTIONS, self.user.attributes)
An update to the user while the action runs survives its completion
316 @enterprise_test() 317 def test_invalid_actions_fail_closed(self): 318 """An action that cannot run keeps the session restricted""" 319 denied = create_action_flow() 320 PolicyBinding.objects.create( 321 policy=DummyPolicy.objects.create( 322 name=generate_id(), result=False, wait_min=0, wait_max=1 323 ), 324 target=denied, 325 order=0, 326 ) 327 self.client.force_login(self.user) 328 for value in (["does-not-exist"], [denied.slug], [42], None, False, 0, "", {}): 329 with self.subTest(value=value): 330 self.require(value) 331 response = self.open_page(reverse("authentik_core:if-user")) 332 self.assertEqual(response.status_code, 403)
An action that cannot run keeps the session restricted
344class TestRequiredActionsMiddleware(RequiredActionsTestCase): 345 """What a session with required actions can and cannot reach""" 346 347 def setUp(self): 348 super().setUp() 349 self.client.force_login(self.user) 350 351 @enterprise_test() 352 def test_api_denied(self): 353 for route in ("authentik_api:application-list", "authentik_api:flow-list"): 354 with self.subTest(route=route): 355 response = self.client.get(reverse(route), HTTP_ACCEPT="application/json") 356 self.assertEqual(response.status_code, 403) 357 358 @enterprise_test() 359 def test_user_cannot_remove_own_actions(self): 360 """Permission to edit themselves doesn't let a user skip their actions""" 361 self.user.assign_perms_to_managed_role("authentik_core.view_user") 362 self.user.assign_perms_to_managed_role("authentik_core.change_user", self.user) 363 response = self.client.patch( 364 reverse("authentik_api:user-detail", kwargs={"pk": self.user.pk}), 365 {"attributes": {}}, 366 format="json", 367 ) 368 self.assertEqual(response.status_code, 403) 369 self.user.refresh_from_db() 370 self.assertEqual(self.user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS], [self.action.slug]) 371 372 @enterprise_test() 373 def test_flow_interface_reads_allowed(self): 374 """The flow interface can load its configuration and user while the API is denied""" 375 self.assertEqual(self.client.get(reverse("authentik_api:brand-list")).status_code, 403) 376 for route in ("authentik_api:user-me", "authentik_api:config"): 377 with self.subTest(route=route): 378 self.assertEqual(self.client.get(reverse(route)).status_code, 200) 379 380 @enterprise_test() 381 def test_other_flow_redirected_to_action(self): 382 other = create_test_flow(FlowDesignation.STAGE_CONFIGURATION) 383 self.assertRedirectsToAction(flow_url(other), self.action) 384 385 @enterprise_test() 386 def test_logout_allowed(self): 387 Flow.objects.filter(designation=FlowDesignation.INVALIDATION).delete() 388 invalidation = create_test_flow(FlowDesignation.INVALIDATION) 389 response = self.client.get(reverse("authentik_flows:default-invalidation")) 390 self.assertEqual(response.status_code, 302) 391 self.assertEqual(response.url, flow_url(invalidation)) 392 self.assertEqual(self.open_page(flow_url(invalidation)).status_code, 200) 393 394 @enterprise_test() 395 def test_impersonation_not_restricted(self): 396 """An administrator impersonating the user isn't sent through their actions""" 397 self.client.force_login(create_test_admin_user()) 398 response = self.client.post( 399 reverse("authentik_api:user-impersonate", kwargs={"pk": self.user.pk}), 400 data={"reason": generate_id()}, 401 ) 402 self.assertEqual(response.status_code, 204) 403 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 404 self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
What a session with required actions can and cannot reach
358 @enterprise_test() 359 def test_user_cannot_remove_own_actions(self): 360 """Permission to edit themselves doesn't let a user skip their actions""" 361 self.user.assign_perms_to_managed_role("authentik_core.view_user") 362 self.user.assign_perms_to_managed_role("authentik_core.change_user", self.user) 363 response = self.client.patch( 364 reverse("authentik_api:user-detail", kwargs={"pk": self.user.pk}), 365 {"attributes": {}}, 366 format="json", 367 ) 368 self.assertEqual(response.status_code, 403) 369 self.user.refresh_from_db() 370 self.assertEqual(self.user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS], [self.action.slug])
Permission to edit themselves doesn't let a user skip their actions
372 @enterprise_test() 373 def test_flow_interface_reads_allowed(self): 374 """The flow interface can load its configuration and user while the API is denied""" 375 self.assertEqual(self.client.get(reverse("authentik_api:brand-list")).status_code, 403) 376 for route in ("authentik_api:user-me", "authentik_api:config"): 377 with self.subTest(route=route): 378 self.assertEqual(self.client.get(reverse(route)).status_code, 200)
The flow interface can load its configuration and user while the API is denied
385 @enterprise_test() 386 def test_logout_allowed(self): 387 Flow.objects.filter(designation=FlowDesignation.INVALIDATION).delete() 388 invalidation = create_test_flow(FlowDesignation.INVALIDATION) 389 response = self.client.get(reverse("authentik_flows:default-invalidation")) 390 self.assertEqual(response.status_code, 302) 391 self.assertEqual(response.url, flow_url(invalidation)) 392 self.assertEqual(self.open_page(flow_url(invalidation)).status_code, 200)
394 @enterprise_test() 395 def test_impersonation_not_restricted(self): 396 """An administrator impersonating the user isn't sent through their actions""" 397 self.client.force_login(create_test_admin_user()) 398 response = self.client.post( 399 reverse("authentik_api:user-impersonate", kwargs={"pk": self.user.pk}), 400 data={"reason": generate_id()}, 401 ) 402 self.assertEqual(response.status_code, 204) 403 self.assertEqual(self.open_page(reverse("authentik_core:if-user")).status_code, 200) 404 self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
An administrator impersonating the user isn't sent through their actions