authentik.flows.tests.test_executor
flow views tests
1"""flow views tests""" 2 3from datetime import timedelta 4from unittest.mock import MagicMock, PropertyMock, patch 5from urllib.parse import urlencode 6 7from django.http import HttpRequest, HttpResponse 8from django.test import override_settings 9from django.urls import reverse 10from django.utils.timezone import now 11from rest_framework.authentication import BaseAuthentication 12from rest_framework.exceptions import ParseError 13 14from authentik.brands.models import Brand 15from authentik.core.models import Group, User 16from authentik.core.tests.utils import RequestFactory, create_test_flow, create_test_user 17from authentik.flows.markers import ReevaluateMarker, StageMarker 18from authentik.flows.models import ( 19 FlowAuthenticationRequirement, 20 FlowDeniedAction, 21 FlowDesignation, 22 FlowStageBinding, 23 FlowToken, 24 InvalidResponseAction, 25) 26from authentik.flows.planner import FlowPlan, FlowPlanner 27from authentik.flows.stage import PLAN_CONTEXT_PENDING_USER_IDENTIFIER, StageView 28from authentik.flows.tests import APIFlowTestCase 29from authentik.flows.views.executor import ( 30 NEXT_ARG_NAME, 31 QS_KEY_TOKEN, 32 QS_QUERY, 33 SESSION_KEY_PLAN, 34 FlowExecutorView, 35) 36from authentik.lib.generators import generate_id 37from authentik.policies.dummy.models import DummyPolicy 38from authentik.policies.models import PolicyBinding 39from authentik.policies.reputation.models import ReputationPolicy 40from authentik.policies.types import PolicyResult 41from authentik.stages.deny.models import DenyStage 42from authentik.stages.dummy.models import DummyStage 43from authentik.stages.identification.models import IdentificationStage, UserFields 44from authentik.stages.password.models import PasswordStage 45 46POLICY_RETURN_FALSE = PropertyMock(return_value=PolicyResult(False, "foo")) 47POLICY_RETURN_TRUE = MagicMock(return_value=PolicyResult(True)) 48 49 50def to_stage_response( 51 request: HttpRequest, 52 source: HttpResponse, 53 final_redirect: bool = False, 54 continuous_login_hold: bool | None = None, 55): 56 """Mock for to_stage_response that returns the original response, so we can check 57 inheritance and member attributes""" 58 return source 59 60 61TO_STAGE_RESPONSE_MOCK = MagicMock(side_effect=to_stage_response) 62 63 64def const_authenticator_factory(user: User) -> type[BaseAuthentication]: 65 66 class ConstAuthenticator(BaseAuthentication): 67 def authenticate(self, request: HttpRequest) -> tuple[User, None]: 68 return (user, None) 69 70 return ConstAuthenticator 71 72 73class TestFlowExecutor(APIFlowTestCase): 74 """Test executor""" 75 76 def setUp(self): 77 self.request_factory = RequestFactory() 78 79 @patch( 80 "authentik.flows.views.executor.to_stage_response", 81 TO_STAGE_RESPONSE_MOCK, 82 ) 83 def test_existing_plan_diff_flow(self): 84 """Check that a plan for a different flow cancels the current plan""" 85 flow = create_test_flow( 86 FlowDesignation.AUTHENTICATION, 87 ) 88 stage = DummyStage.objects.create(name=generate_id()) 89 binding = FlowStageBinding(target=flow, stage=stage, order=0) 90 plan = FlowPlan(flow_pk=flow.pk.hex + "a", bindings=[binding], markers=[StageMarker()]) 91 session = self.client.session 92 session[SESSION_KEY_PLAN] = plan 93 session.save() 94 95 cancel_mock = MagicMock() 96 with patch("authentik.flows.views.executor.FlowExecutorView.cancel", cancel_mock): 97 response = self.client.get( 98 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 99 ) 100 self.assertEqual(response.status_code, 302) 101 self.assertEqual(cancel_mock.call_count, 2) 102 103 @patch( 104 "authentik.flows.views.executor.to_stage_response", 105 TO_STAGE_RESPONSE_MOCK, 106 ) 107 @patch( 108 "authentik.policies.engine.PolicyEngine.result", 109 POLICY_RETURN_FALSE, 110 ) 111 def test_invalid_non_applicable_flow(self): 112 """Tests that a non-applicable flow returns the correct error message""" 113 flow = create_test_flow( 114 FlowDesignation.AUTHENTICATION, 115 ) 116 117 response = self.client.get( 118 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 119 ) 120 self.assertStageResponse( 121 response, 122 flow=flow, 123 error_message="foo", 124 component="ak-stage-access-denied", 125 ) 126 127 @patch( 128 "authentik.flows.views.executor.to_stage_response", 129 TO_STAGE_RESPONSE_MOCK, 130 ) 131 @patch( 132 "authentik.policies.engine.PolicyEngine.result", 133 POLICY_RETURN_FALSE, 134 ) 135 def test_invalid_non_applicable_flow_continue(self): 136 """Tests that a non-applicable flow that should redirect""" 137 flow = create_test_flow( 138 FlowDesignation.AUTHENTICATION, 139 denied_action=FlowDeniedAction.CONTINUE, 140 ) 141 142 response = self.client.get( 143 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 144 ) 145 self.assertEqual(response.status_code, 302) 146 self.assertEqual(response.url, reverse("authentik_core:root-redirect")) 147 148 @patch( 149 "authentik.flows.views.executor.to_stage_response", 150 TO_STAGE_RESPONSE_MOCK, 151 ) 152 def test_invalid_flow_redirect(self): 153 """Test invalid flow with valid redirect destination""" 154 flow = create_test_flow( 155 FlowDesignation.AUTHENTICATION, 156 ) 157 158 dest = "/unique-string" 159 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 160 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 161 self.assertEqual(response.status_code, 302) 162 self.assertEqual(response.url, "/unique-string") 163 164 @patch( 165 "authentik.flows.views.executor.to_stage_response", 166 TO_STAGE_RESPONSE_MOCK, 167 ) 168 def test_invalid_flow_invalid_redirect(self): 169 """Test invalid flow redirect with an invalid URL""" 170 flow = create_test_flow( 171 FlowDesignation.AUTHENTICATION, 172 ) 173 174 dest = "http://something.example.com/unique-string" 175 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 176 177 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 178 self.assertEqual(response.status_code, 200) 179 self.assertStageResponse( 180 response, 181 flow, 182 component="ak-stage-access-denied", 183 error_message="Invalid next URL", 184 ) 185 186 @patch( 187 "authentik.flows.views.executor.to_stage_response", 188 TO_STAGE_RESPONSE_MOCK, 189 ) 190 def test_valid_flow_redirect(self): 191 """Test valid flow with valid redirect destination""" 192 flow = create_test_flow() 193 194 dest = "/unique-string" 195 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 196 197 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 198 self.assertEqual(response.status_code, 302) 199 self.assertEqual(response.url, "/unique-string") 200 201 def test_flow_done_redirect_challenge_is_final(self): 202 """Test redirects generated when a flow is done are marked as final.""" 203 flow = create_test_flow() 204 205 dest = "/unique-string" 206 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 207 208 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 209 210 self.assertStageResponse( 211 response, 212 component="xak-flow-redirect", 213 to=dest, 214 final_redirect=True, 215 ) 216 217 @patch( 218 "authentik.flows.views.executor.to_stage_response", 219 TO_STAGE_RESPONSE_MOCK, 220 ) 221 def test_valid_flow_redirect_authenticated(self): 222 """Test valid flow with valid redirect destination, authenticated already""" 223 flow = create_test_flow() 224 flow.designation = FlowDesignation.AUTHENTICATION 225 flow.authentication = FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED 226 flow.save() 227 self.client.force_login(create_test_user()) 228 229 dest = "/unique-string" 230 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 231 232 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 233 self.assertEqual(response.status_code, 302) 234 self.assertEqual(response.url, "/unique-string") 235 236 @patch( 237 "authentik.flows.views.executor.to_stage_response", 238 TO_STAGE_RESPONSE_MOCK, 239 ) 240 def test_valid_flow_invalid_redirect(self): 241 """Test valid flow redirect with an invalid URL""" 242 flow = create_test_flow() 243 244 dest = "http://something.example.com/unique-string" 245 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 246 247 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 248 self.assertEqual(response.status_code, 200) 249 self.assertStageResponse( 250 response, 251 flow, 252 component="ak-stage-access-denied", 253 error_message="Invalid next URL", 254 ) 255 256 @patch( 257 "authentik.flows.views.executor.to_stage_response", 258 TO_STAGE_RESPONSE_MOCK, 259 ) 260 def test_invalid_empty_flow(self): 261 """Tests that an empty flow returns the correct error message""" 262 flow = create_test_flow( 263 FlowDesignation.AUTHENTICATION, 264 ) 265 266 response = self.client.get( 267 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 268 ) 269 self.assertEqual(response.status_code, 302) 270 self.assertEqual(response.url, reverse("authentik_core:root-redirect")) 271 272 def test_multi_stage_flow(self): 273 """Test a full flow with multiple stages""" 274 flow = create_test_flow( 275 FlowDesignation.AUTHENTICATION, 276 ) 277 FlowStageBinding.objects.create( 278 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 279 ) 280 FlowStageBinding.objects.create( 281 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=1 282 ) 283 284 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 285 # First Request, start planning, renders form 286 response = self.client.get(exec_url) 287 self.assertEqual(response.status_code, 200) 288 # Check that two stages are in plan 289 session = self.client.session 290 plan: FlowPlan = session[SESSION_KEY_PLAN] 291 self.assertEqual(len(plan.bindings), 2) 292 # Second request, submit form, one stage left 293 response = self.client.post(exec_url) 294 # Second request redirects to the same URL 295 self.assertEqual(response.status_code, 302) 296 self.assertEqual(response.url, exec_url) 297 # Check that two stages are in plan 298 session = self.client.session 299 plan: FlowPlan = session[SESSION_KEY_PLAN] 300 self.assertEqual(len(plan.bindings), 1) 301 302 @patch( 303 "authentik.flows.views.executor.to_stage_response", 304 TO_STAGE_RESPONSE_MOCK, 305 ) 306 def test_reevaluate_remove_last(self): 307 """Test planner with re-evaluate (last stage is removed)""" 308 flow = create_test_flow( 309 FlowDesignation.AUTHENTICATION, 310 ) 311 false_policy = DummyPolicy.objects.create( 312 name=generate_id(), result=False, wait_min=1, wait_max=2 313 ) 314 315 binding = FlowStageBinding.objects.create( 316 target=flow, 317 stage=DummyStage.objects.create(name=generate_id()), 318 order=0, 319 evaluate_on_plan=True, 320 re_evaluate_policies=False, 321 ) 322 binding2 = FlowStageBinding.objects.create( 323 target=flow, 324 stage=DummyStage.objects.create(name=generate_id()), 325 order=1, 326 re_evaluate_policies=True, 327 ) 328 329 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 330 331 # Here we patch the dummy policy to evaluate to true so the stage is included 332 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 333 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 334 # First request, run the planner 335 response = self.client.get(exec_url) 336 self.assertEqual(response.status_code, 200) 337 338 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 339 340 self.assertEqual(plan.bindings[0], binding) 341 self.assertEqual(plan.bindings[1], binding2) 342 343 self.assertEqual(plan.markers[0].__class__, StageMarker) 344 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 345 346 # Second request, this passes the first dummy stage 347 response = self.client.post(exec_url) 348 self.assertEqual(response.status_code, 302) 349 350 # third request, this should trigger the re-evaluate 351 # We do this request without the patch, so the policy results in false 352 response = self.client.post(exec_url) 353 self.assertEqual(response.status_code, 302) 354 self.assertEqual(response.url, reverse("authentik_core:root-redirect")) 355 356 def test_reevaluate_remove_middle(self): 357 """Test planner with re-evaluate (middle stage is removed)""" 358 flow = create_test_flow( 359 FlowDesignation.AUTHENTICATION, 360 ) 361 false_policy = DummyPolicy.objects.create( 362 name=generate_id(), result=False, wait_min=1, wait_max=2 363 ) 364 365 binding = FlowStageBinding.objects.create( 366 target=flow, 367 stage=DummyStage.objects.create(name=generate_id()), 368 order=0, 369 evaluate_on_plan=True, 370 re_evaluate_policies=False, 371 ) 372 binding2 = FlowStageBinding.objects.create( 373 target=flow, 374 stage=DummyStage.objects.create(name=generate_id()), 375 order=1, 376 re_evaluate_policies=True, 377 ) 378 binding3 = FlowStageBinding.objects.create( 379 target=flow, 380 stage=DummyStage.objects.create(name=generate_id()), 381 order=2, 382 evaluate_on_plan=True, 383 re_evaluate_policies=False, 384 ) 385 386 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 387 388 # Here we patch the dummy policy to evaluate to true so the stage is included 389 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 390 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 391 # First request, run the planner 392 response = self.client.get(exec_url) 393 394 self.assertEqual(response.status_code, 200) 395 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 396 397 self.assertEqual(plan.bindings[0], binding) 398 self.assertEqual(plan.bindings[1], binding2) 399 self.assertEqual(plan.bindings[2], binding3) 400 401 self.assertEqual(plan.markers[0].__class__, StageMarker) 402 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 403 self.assertEqual(plan.markers[2].__class__, StageMarker) 404 405 # Second request, this passes the first dummy stage 406 response = self.client.post(exec_url) 407 self.assertEqual(response.status_code, 302) 408 409 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 410 411 self.assertEqual(plan.bindings[0], binding2) 412 self.assertEqual(plan.bindings[1], binding3) 413 414 self.assertEqual(plan.markers[0].__class__, ReevaluateMarker) 415 self.assertEqual(plan.markers[1].__class__, StageMarker) 416 417 # third request, this should trigger the re-evaluate 418 # We do this request without the patch, so the policy results in false 419 response = self.client.post(exec_url) 420 self.assertEqual(response.status_code, 200) 421 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 422 423 def test_reevaluate_keep(self): 424 """Test planner with re-evaluate (everything is kept)""" 425 flow = create_test_flow( 426 FlowDesignation.AUTHENTICATION, 427 ) 428 true_policy = DummyPolicy.objects.create( 429 name=generate_id(), result=True, wait_min=1, wait_max=2 430 ) 431 432 binding = FlowStageBinding.objects.create( 433 target=flow, 434 stage=DummyStage.objects.create(name=generate_id()), 435 order=0, 436 evaluate_on_plan=True, 437 re_evaluate_policies=False, 438 ) 439 binding2 = FlowStageBinding.objects.create( 440 target=flow, 441 stage=DummyStage.objects.create(name=generate_id()), 442 order=1, 443 re_evaluate_policies=True, 444 ) 445 binding3 = FlowStageBinding.objects.create( 446 target=flow, 447 stage=DummyStage.objects.create(name=generate_id()), 448 order=2, 449 evaluate_on_plan=True, 450 re_evaluate_policies=False, 451 ) 452 453 PolicyBinding.objects.create(policy=true_policy, target=binding2, order=0) 454 455 # Here we patch the dummy policy to evaluate to true so the stage is included 456 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 457 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 458 # First request, run the planner 459 response = self.client.get(exec_url) 460 461 self.assertEqual(response.status_code, 200) 462 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 463 464 self.assertEqual(plan.bindings[0], binding) 465 self.assertEqual(plan.bindings[1], binding2) 466 self.assertEqual(plan.bindings[2], binding3) 467 468 self.assertEqual(plan.markers[0].__class__, StageMarker) 469 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 470 self.assertEqual(plan.markers[2].__class__, StageMarker) 471 472 # Second request, this passes the first dummy stage 473 response = self.client.post(exec_url) 474 self.assertEqual(response.status_code, 302) 475 476 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 477 478 self.assertEqual(plan.bindings[0], binding2) 479 self.assertEqual(plan.bindings[1], binding3) 480 481 self.assertEqual(plan.markers[0].__class__, ReevaluateMarker) 482 self.assertEqual(plan.markers[1].__class__, StageMarker) 483 484 # Third request, this passes the first dummy stage 485 response = self.client.post(exec_url) 486 self.assertEqual(response.status_code, 302) 487 488 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 489 490 self.assertEqual(plan.bindings[0], binding3) 491 492 self.assertEqual(plan.markers[0].__class__, StageMarker) 493 494 # third request, this should trigger the re-evaluate 495 # We do this request without the patch, so the policy results in false 496 response = self.client.post(exec_url) 497 self.assertEqual(response.status_code, 200) 498 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 499 500 def test_reevaluate_remove_consecutive(self): 501 """Test planner with re-evaluate (consecutive stages are removed)""" 502 flow = create_test_flow( 503 FlowDesignation.AUTHENTICATION, 504 ) 505 false_policy = DummyPolicy.objects.create( 506 name=generate_id(), result=False, wait_min=1, wait_max=2 507 ) 508 509 binding = FlowStageBinding.objects.create( 510 target=flow, 511 stage=DummyStage.objects.create(name=generate_id()), 512 order=0, 513 evaluate_on_plan=True, 514 re_evaluate_policies=False, 515 ) 516 binding2 = FlowStageBinding.objects.create( 517 target=flow, 518 stage=DummyStage.objects.create(name=generate_id()), 519 order=1, 520 re_evaluate_policies=True, 521 ) 522 binding3 = FlowStageBinding.objects.create( 523 target=flow, 524 stage=DummyStage.objects.create(name=generate_id()), 525 order=2, 526 re_evaluate_policies=True, 527 ) 528 binding4 = FlowStageBinding.objects.create( 529 target=flow, 530 stage=DummyStage.objects.create(name=generate_id()), 531 order=2, 532 evaluate_on_plan=True, 533 re_evaluate_policies=False, 534 ) 535 536 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 537 PolicyBinding.objects.create(policy=false_policy, target=binding3, order=0) 538 539 # Here we patch the dummy policy to evaluate to true so the stage is included 540 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 541 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 542 # First request, run the planner 543 response = self.client.get(exec_url) 544 self.assertEqual(response.status_code, 200) 545 self.assertStageResponse(response, flow, component="ak-stage-dummy") 546 547 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 548 549 self.assertEqual(plan.bindings[0], binding) 550 self.assertEqual(plan.bindings[1], binding2) 551 self.assertEqual(plan.bindings[2], binding3) 552 self.assertEqual(plan.bindings[3], binding4) 553 554 self.assertEqual(plan.markers[0].__class__, StageMarker) 555 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 556 self.assertEqual(plan.markers[2].__class__, ReevaluateMarker) 557 self.assertEqual(plan.markers[3].__class__, StageMarker) 558 559 # Second request, this passes the first dummy stage 560 response = self.client.post(exec_url) 561 self.assertEqual(response.status_code, 302) 562 563 # third request, this should trigger the re-evaluate 564 # A get request will evaluate the policies and this will return stage 4 565 # but it won't save it, hence we can't check the plan 566 response = self.client.get(exec_url) 567 self.assertStageResponse(response, flow, component="ak-stage-dummy") 568 569 # fourth request, this confirms the last stage (dummy4) 570 # We do this request without the patch, so the policy results in false 571 response = self.client.post(exec_url) 572 self.assertEqual(response.status_code, 200) 573 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 574 575 def test_stageview_user_identifier(self): 576 """Test PLAN_CONTEXT_PENDING_USER_IDENTIFIER""" 577 flow = create_test_flow( 578 FlowDesignation.AUTHENTICATION, 579 ) 580 FlowStageBinding.objects.create( 581 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 582 ) 583 584 ident = "test-identifier" 585 586 user = User.objects.create(username="test-user") 587 request = self.request_factory.get( 588 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 589 ) 590 request.user = user 591 planner = FlowPlanner(flow) 592 plan = planner.plan(request, default_context={PLAN_CONTEXT_PENDING_USER_IDENTIFIER: ident}) 593 594 executor = FlowExecutorView() 595 executor.plan = plan 596 executor.flow = flow 597 598 stage_view = StageView(executor) 599 self.assertEqual(ident, stage_view.get_pending_user(for_display=True).username) 600 601 def test_flow_executor_respect_authentication_classes(self): 602 """Test with authentication_classes""" 603 flow = create_test_flow( 604 FlowDesignation.STAGE_CONFIGURATION, 605 authentication=FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED, 606 ) 607 FlowStageBinding.objects.create( 608 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 609 ) 610 611 user = create_test_user() 612 613 def prepare(): 614 request = self.request_factory.get( 615 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 616 ) 617 request.session = {} 618 request.brand = Brand(domain="fallback") 619 620 executor = FlowExecutorView() 621 622 executor.setup(request, flow_slug=flow.slug) 623 624 return request, executor 625 626 # Flow execution should not work in this case, since no user is authenticated, 627 # but authentication is required. 628 with self.subTest("User should not be respected without authentication middleware"): 629 request, executor = prepare() 630 631 executor.authentication_classes = [] 632 633 with patch.object( 634 FlowExecutorView, "handle_invalid_flow", return_value=HttpResponse() 635 ) as handle_invalid_flow: 636 executor.dispatch(request, flow_slug=flow.slug) 637 638 handle_invalid_flow.assert_called_once() 639 640 # Authentication should work in this case, since the user is injected 641 # through a custom authentication class. 642 with self.subTest("User should be respected from authentication middleware"): 643 request, executor = prepare() 644 645 # Inject ConstAuthenticator that always returns 'user' 646 executor.authentication_classes = [const_authenticator_factory(user)] 647 648 with patch.object( 649 FlowExecutorView, "handle_invalid_flow", return_value=HttpResponse() 650 ) as handle_invalid_flow: 651 executor.dispatch(request, flow_slug=flow.slug) 652 653 handle_invalid_flow.assert_not_called() 654 655 def test_invalid_restart(self): 656 """Test flow that restarts on invalid entry""" 657 flow = create_test_flow( 658 FlowDesignation.AUTHENTICATION, 659 ) 660 # Stage 0 is a deny stage that is added dynamically 661 # when the reputation policy says so 662 deny_stage = DenyStage.objects.create(name=generate_id()) 663 reputation_policy = ReputationPolicy.objects.create( 664 name=generate_id(), threshold=-1, check_ip=False 665 ) 666 deny_binding = FlowStageBinding.objects.create( 667 target=flow, 668 stage=deny_stage, 669 order=0, 670 evaluate_on_plan=False, 671 re_evaluate_policies=True, 672 ) 673 PolicyBinding.objects.create(policy=reputation_policy, target=deny_binding, order=0) 674 675 # Stage 1 is an identification stage 676 ident_stage = IdentificationStage.objects.create( 677 name=generate_id(), 678 user_fields=[UserFields.E_MAIL], 679 pretend_user_exists=False, 680 ) 681 FlowStageBinding.objects.create( 682 target=flow, 683 stage=ident_stage, 684 order=1, 685 invalid_response_action=InvalidResponseAction.RESTART_WITH_CONTEXT, 686 ) 687 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 688 # First request, run the planner 689 response = self.client.get(exec_url) 690 self.assertStageResponse( 691 response, 692 flow, 693 component="ak-stage-identification", 694 password_fields=False, 695 primary_action="Log in", 696 sources=[], 697 show_source_labels=False, 698 user_fields=[UserFields.E_MAIL], 699 ) 700 response = self.client.post(exec_url, {"uid_field": "invalid-string"}, follow=True) 701 self.assertStageResponse(response, flow, component="ak-stage-access-denied") 702 703 def test_re_evaluate_group_binding(self): 704 """Test re-evaluate stage binding that has a policy binding to a group""" 705 flow = create_test_flow() 706 707 user_group_membership = create_test_user() 708 user_direct_binding = create_test_user() 709 user_other = create_test_user() 710 711 group_a = Group.objects.create(name=generate_id()) 712 user_group_membership.groups.add(group_a) 713 714 # Stage 0 is an identification stage 715 ident_stage = IdentificationStage.objects.create( 716 name=generate_id(), 717 user_fields=[UserFields.USERNAME], 718 pretend_user_exists=False, 719 ) 720 FlowStageBinding.objects.create( 721 target=flow, 722 stage=ident_stage, 723 order=0, 724 ) 725 726 # Stage 1 is a dummy stage that is only shown for users in group_a 727 dummy_stage = DummyStage.objects.create(name=generate_id()) 728 dummy_binding = FlowStageBinding.objects.create(target=flow, stage=dummy_stage, order=1) 729 PolicyBinding.objects.create(group=group_a, target=dummy_binding, order=0) 730 PolicyBinding.objects.create(user=user_direct_binding, target=dummy_binding, order=0) 731 732 # Stage 2 is a deny stage that (in this case) only user_b will see 733 deny_stage = DenyStage.objects.create(name=generate_id()) 734 FlowStageBinding.objects.create(target=flow, stage=deny_stage, order=2) 735 736 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 737 738 with self.subTest(f"Test user access through group: {user_group_membership}"): 739 self.client.logout() 740 # First request, run the planner 741 response = self.client.get(exec_url) 742 self.assertStageResponse(response, flow, component="ak-stage-identification") 743 response = self.client.post( 744 exec_url, {"uid_field": user_group_membership.username}, follow=True 745 ) 746 self.assertStageResponse(response, flow, component="ak-stage-dummy") 747 with self.subTest(f"Test user access through user: {user_direct_binding}"): 748 self.client.logout() 749 # First request, run the planner 750 response = self.client.get(exec_url) 751 self.assertStageResponse(response, flow, component="ak-stage-identification") 752 response = self.client.post( 753 exec_url, {"uid_field": user_direct_binding.username}, follow=True 754 ) 755 self.assertStageResponse(response, flow, component="ak-stage-dummy") 756 with self.subTest(f"Test user has no access: {user_other}"): 757 self.client.logout() 758 # First request, run the planner 759 response = self.client.get(exec_url) 760 self.assertStageResponse(response, flow, component="ak-stage-identification") 761 response = self.client.post(exec_url, {"uid_field": user_other.username}, follow=True) 762 self.assertStageResponse(response, flow, component="ak-stage-access-denied") 763 764 @patch( 765 "authentik.flows.views.executor.to_stage_response", 766 TO_STAGE_RESPONSE_MOCK, 767 ) 768 def test_invalid_json(self): 769 """Test invalid JSON body""" 770 flow = create_test_flow() 771 FlowStageBinding.objects.create( 772 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 773 ) 774 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 775 776 with override_settings(TEST=False, DEBUG=False): 777 self.client.logout() 778 response = self.client.post(url, data="{", content_type="application/json") 779 self.assertEqual(response.status_code, 200) 780 781 with self.assertRaises(ParseError): 782 self.client.logout() 783 response = self.client.post(url, data="{", content_type="application/json") 784 self.assertEqual(response.status_code, 200) 785 786 def test_cancel_next(self): 787 """Test cancel URL with ?next param set""" 788 flow = create_test_flow() 789 790 # Stage 0 is an identification stage 791 ident_stage = IdentificationStage.objects.create( 792 name=generate_id(), 793 user_fields=[UserFields.USERNAME], 794 ) 795 FlowStageBinding.objects.create( 796 target=flow, 797 stage=ident_stage, 798 order=0, 799 ) 800 801 # Stage 1 is a password stage 802 password_stage = PasswordStage.objects.create(name=generate_id(), backends=[]) 803 FlowStageBinding.objects.create( 804 target=flow, 805 stage=password_stage, 806 order=1, 807 ) 808 res = self.client.get( 809 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 810 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}" 811 ) 812 self.assertStageResponse(res, flow, component="ak-stage-identification") 813 814 res = self.client.post( 815 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 816 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}", 817 data={"component": "ak-stage-identification", "uid_field": generate_id()}, 818 follow=True, 819 ) 820 self.assertEqual(res.status_code, 200) 821 self.assertStageResponse( 822 res, 823 flow, 824 flow_info={ 825 "background": "/static/dist/assets/images/flow_background.jpg", 826 "background_themed_urls": None, 827 "cancel_url": "/flows/-/cancel/?next=%2Ffoo", 828 "layout": "stacked", 829 "title": flow.title, 830 "messages": [], 831 }, 832 ) 833 834 def test_cancel_next_access_denied(self): 835 """Test cancel URL on the access denied page with ?next param set""" 836 flow = create_test_flow() 837 FlowStageBinding.objects.create( 838 target=flow, 839 stage=DenyStage.objects.create(name=generate_id()), 840 order=0, 841 ) 842 res = self.client.get( 843 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 844 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}" 845 ) 846 body = self.assertStageResponse(res, flow, component="ak-stage-access-denied") 847 self.assertEqual(body["flow_info"]["cancel_url"], "/flows/-/cancel/?next=%2Ffoo") 848 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 849 850 res = self.client.get(body["flow_info"]["cancel_url"]) 851 self.assertRedirects(res, "/foo", fetch_redirect_response=False) 852 853 @patch( 854 "authentik.flows.views.executor.to_stage_response", 855 TO_STAGE_RESPONSE_MOCK, 856 ) 857 def test_expired_flow_token(self): 858 """Test that an expired flow token shows an appropriate error message""" 859 flow = create_test_flow( 860 FlowDesignation.RECOVERY, 861 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 862 ) 863 user = create_test_user() 864 plan = FlowPlan(flow_pk=flow.pk.hex, bindings=[], markers=[]) 865 866 token = FlowToken.objects.create( 867 user=user, 868 identifier=generate_id(), 869 flow=flow, 870 _plan=FlowToken.pickle(plan), 871 expires=now() - timedelta(hours=1), 872 ) 873 874 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 875 response = self.client.get( 876 url + f"?{urlencode({QS_QUERY: urlencode({QS_KEY_TOKEN: token.key})})}" 877 ) 878 self.assertStageResponse( 879 response, 880 flow, 881 component="ak-stage-access-denied", 882 error_message="This link is invalid or has expired. Please request a new one.", 883 ) 884 885 @patch( 886 "authentik.flows.views.executor.to_stage_response", 887 TO_STAGE_RESPONSE_MOCK, 888 ) 889 def test_invalid_flow_token_require_token(self): 890 """Test that an invalid/nonexistent token on a REQUIRE_TOKEN flow shows error""" 891 flow = create_test_flow( 892 FlowDesignation.RECOVERY, 893 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 894 ) 895 896 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 897 response = self.client.get( 898 url + f"?{urlencode({QS_QUERY: urlencode({QS_KEY_TOKEN: 'invalid-token'})})}" 899 ) 900 self.assertStageResponse( 901 response, 902 flow, 903 component="ak-stage-access-denied", 904 error_message="This link is invalid or has expired. Please request a new one.", 905 ) 906 907 @patch( 908 "authentik.flows.views.executor.to_stage_response", 909 TO_STAGE_RESPONSE_MOCK, 910 ) 911 def test_no_token_require_token(self): 912 """Test that accessing a REQUIRE_TOKEN flow without any token shows error""" 913 flow = create_test_flow( 914 FlowDesignation.RECOVERY, 915 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 916 ) 917 918 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 919 response = self.client.get(url) 920 self.assertStageResponse( 921 response, 922 flow, 923 component="ak-stage-access-denied", 924 error_message="This link is invalid or has expired. Please request a new one.", 925 )
A mock intended to be used as a property, or other descriptor, on a class.
PropertyMock provides __get__ and __set__ methods so you can specify
a return value when it is fetched.
Fetching a PropertyMock instance from an object calls the mock, with
no args. Setting it calls the mock with the value being set.
51def to_stage_response( 52 request: HttpRequest, 53 source: HttpResponse, 54 final_redirect: bool = False, 55 continuous_login_hold: bool | None = None, 56): 57 """Mock for to_stage_response that returns the original response, so we can check 58 inheritance and member attributes""" 59 return source
Mock for to_stage_response that returns the original response, so we can check inheritance and member attributes
74class TestFlowExecutor(APIFlowTestCase): 75 """Test executor""" 76 77 def setUp(self): 78 self.request_factory = RequestFactory() 79 80 @patch( 81 "authentik.flows.views.executor.to_stage_response", 82 TO_STAGE_RESPONSE_MOCK, 83 ) 84 def test_existing_plan_diff_flow(self): 85 """Check that a plan for a different flow cancels the current plan""" 86 flow = create_test_flow( 87 FlowDesignation.AUTHENTICATION, 88 ) 89 stage = DummyStage.objects.create(name=generate_id()) 90 binding = FlowStageBinding(target=flow, stage=stage, order=0) 91 plan = FlowPlan(flow_pk=flow.pk.hex + "a", bindings=[binding], markers=[StageMarker()]) 92 session = self.client.session 93 session[SESSION_KEY_PLAN] = plan 94 session.save() 95 96 cancel_mock = MagicMock() 97 with patch("authentik.flows.views.executor.FlowExecutorView.cancel", cancel_mock): 98 response = self.client.get( 99 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 100 ) 101 self.assertEqual(response.status_code, 302) 102 self.assertEqual(cancel_mock.call_count, 2) 103 104 @patch( 105 "authentik.flows.views.executor.to_stage_response", 106 TO_STAGE_RESPONSE_MOCK, 107 ) 108 @patch( 109 "authentik.policies.engine.PolicyEngine.result", 110 POLICY_RETURN_FALSE, 111 ) 112 def test_invalid_non_applicable_flow(self): 113 """Tests that a non-applicable flow returns the correct error message""" 114 flow = create_test_flow( 115 FlowDesignation.AUTHENTICATION, 116 ) 117 118 response = self.client.get( 119 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 120 ) 121 self.assertStageResponse( 122 response, 123 flow=flow, 124 error_message="foo", 125 component="ak-stage-access-denied", 126 ) 127 128 @patch( 129 "authentik.flows.views.executor.to_stage_response", 130 TO_STAGE_RESPONSE_MOCK, 131 ) 132 @patch( 133 "authentik.policies.engine.PolicyEngine.result", 134 POLICY_RETURN_FALSE, 135 ) 136 def test_invalid_non_applicable_flow_continue(self): 137 """Tests that a non-applicable flow that should redirect""" 138 flow = create_test_flow( 139 FlowDesignation.AUTHENTICATION, 140 denied_action=FlowDeniedAction.CONTINUE, 141 ) 142 143 response = self.client.get( 144 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 145 ) 146 self.assertEqual(response.status_code, 302) 147 self.assertEqual(response.url, reverse("authentik_core:root-redirect")) 148 149 @patch( 150 "authentik.flows.views.executor.to_stage_response", 151 TO_STAGE_RESPONSE_MOCK, 152 ) 153 def test_invalid_flow_redirect(self): 154 """Test invalid flow with valid redirect destination""" 155 flow = create_test_flow( 156 FlowDesignation.AUTHENTICATION, 157 ) 158 159 dest = "/unique-string" 160 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 161 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 162 self.assertEqual(response.status_code, 302) 163 self.assertEqual(response.url, "/unique-string") 164 165 @patch( 166 "authentik.flows.views.executor.to_stage_response", 167 TO_STAGE_RESPONSE_MOCK, 168 ) 169 def test_invalid_flow_invalid_redirect(self): 170 """Test invalid flow redirect with an invalid URL""" 171 flow = create_test_flow( 172 FlowDesignation.AUTHENTICATION, 173 ) 174 175 dest = "http://something.example.com/unique-string" 176 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 177 178 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 179 self.assertEqual(response.status_code, 200) 180 self.assertStageResponse( 181 response, 182 flow, 183 component="ak-stage-access-denied", 184 error_message="Invalid next URL", 185 ) 186 187 @patch( 188 "authentik.flows.views.executor.to_stage_response", 189 TO_STAGE_RESPONSE_MOCK, 190 ) 191 def test_valid_flow_redirect(self): 192 """Test valid flow with valid redirect destination""" 193 flow = create_test_flow() 194 195 dest = "/unique-string" 196 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 197 198 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 199 self.assertEqual(response.status_code, 302) 200 self.assertEqual(response.url, "/unique-string") 201 202 def test_flow_done_redirect_challenge_is_final(self): 203 """Test redirects generated when a flow is done are marked as final.""" 204 flow = create_test_flow() 205 206 dest = "/unique-string" 207 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 208 209 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 210 211 self.assertStageResponse( 212 response, 213 component="xak-flow-redirect", 214 to=dest, 215 final_redirect=True, 216 ) 217 218 @patch( 219 "authentik.flows.views.executor.to_stage_response", 220 TO_STAGE_RESPONSE_MOCK, 221 ) 222 def test_valid_flow_redirect_authenticated(self): 223 """Test valid flow with valid redirect destination, authenticated already""" 224 flow = create_test_flow() 225 flow.designation = FlowDesignation.AUTHENTICATION 226 flow.authentication = FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED 227 flow.save() 228 self.client.force_login(create_test_user()) 229 230 dest = "/unique-string" 231 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 232 233 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 234 self.assertEqual(response.status_code, 302) 235 self.assertEqual(response.url, "/unique-string") 236 237 @patch( 238 "authentik.flows.views.executor.to_stage_response", 239 TO_STAGE_RESPONSE_MOCK, 240 ) 241 def test_valid_flow_invalid_redirect(self): 242 """Test valid flow redirect with an invalid URL""" 243 flow = create_test_flow() 244 245 dest = "http://something.example.com/unique-string" 246 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 247 248 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 249 self.assertEqual(response.status_code, 200) 250 self.assertStageResponse( 251 response, 252 flow, 253 component="ak-stage-access-denied", 254 error_message="Invalid next URL", 255 ) 256 257 @patch( 258 "authentik.flows.views.executor.to_stage_response", 259 TO_STAGE_RESPONSE_MOCK, 260 ) 261 def test_invalid_empty_flow(self): 262 """Tests that an empty flow returns the correct error message""" 263 flow = create_test_flow( 264 FlowDesignation.AUTHENTICATION, 265 ) 266 267 response = self.client.get( 268 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 269 ) 270 self.assertEqual(response.status_code, 302) 271 self.assertEqual(response.url, reverse("authentik_core:root-redirect")) 272 273 def test_multi_stage_flow(self): 274 """Test a full flow with multiple stages""" 275 flow = create_test_flow( 276 FlowDesignation.AUTHENTICATION, 277 ) 278 FlowStageBinding.objects.create( 279 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 280 ) 281 FlowStageBinding.objects.create( 282 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=1 283 ) 284 285 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 286 # First Request, start planning, renders form 287 response = self.client.get(exec_url) 288 self.assertEqual(response.status_code, 200) 289 # Check that two stages are in plan 290 session = self.client.session 291 plan: FlowPlan = session[SESSION_KEY_PLAN] 292 self.assertEqual(len(plan.bindings), 2) 293 # Second request, submit form, one stage left 294 response = self.client.post(exec_url) 295 # Second request redirects to the same URL 296 self.assertEqual(response.status_code, 302) 297 self.assertEqual(response.url, exec_url) 298 # Check that two stages are in plan 299 session = self.client.session 300 plan: FlowPlan = session[SESSION_KEY_PLAN] 301 self.assertEqual(len(plan.bindings), 1) 302 303 @patch( 304 "authentik.flows.views.executor.to_stage_response", 305 TO_STAGE_RESPONSE_MOCK, 306 ) 307 def test_reevaluate_remove_last(self): 308 """Test planner with re-evaluate (last stage is removed)""" 309 flow = create_test_flow( 310 FlowDesignation.AUTHENTICATION, 311 ) 312 false_policy = DummyPolicy.objects.create( 313 name=generate_id(), result=False, wait_min=1, wait_max=2 314 ) 315 316 binding = FlowStageBinding.objects.create( 317 target=flow, 318 stage=DummyStage.objects.create(name=generate_id()), 319 order=0, 320 evaluate_on_plan=True, 321 re_evaluate_policies=False, 322 ) 323 binding2 = FlowStageBinding.objects.create( 324 target=flow, 325 stage=DummyStage.objects.create(name=generate_id()), 326 order=1, 327 re_evaluate_policies=True, 328 ) 329 330 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 331 332 # Here we patch the dummy policy to evaluate to true so the stage is included 333 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 334 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 335 # First request, run the planner 336 response = self.client.get(exec_url) 337 self.assertEqual(response.status_code, 200) 338 339 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 340 341 self.assertEqual(plan.bindings[0], binding) 342 self.assertEqual(plan.bindings[1], binding2) 343 344 self.assertEqual(plan.markers[0].__class__, StageMarker) 345 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 346 347 # Second request, this passes the first dummy stage 348 response = self.client.post(exec_url) 349 self.assertEqual(response.status_code, 302) 350 351 # third request, this should trigger the re-evaluate 352 # We do this request without the patch, so the policy results in false 353 response = self.client.post(exec_url) 354 self.assertEqual(response.status_code, 302) 355 self.assertEqual(response.url, reverse("authentik_core:root-redirect")) 356 357 def test_reevaluate_remove_middle(self): 358 """Test planner with re-evaluate (middle stage is removed)""" 359 flow = create_test_flow( 360 FlowDesignation.AUTHENTICATION, 361 ) 362 false_policy = DummyPolicy.objects.create( 363 name=generate_id(), result=False, wait_min=1, wait_max=2 364 ) 365 366 binding = FlowStageBinding.objects.create( 367 target=flow, 368 stage=DummyStage.objects.create(name=generate_id()), 369 order=0, 370 evaluate_on_plan=True, 371 re_evaluate_policies=False, 372 ) 373 binding2 = FlowStageBinding.objects.create( 374 target=flow, 375 stage=DummyStage.objects.create(name=generate_id()), 376 order=1, 377 re_evaluate_policies=True, 378 ) 379 binding3 = FlowStageBinding.objects.create( 380 target=flow, 381 stage=DummyStage.objects.create(name=generate_id()), 382 order=2, 383 evaluate_on_plan=True, 384 re_evaluate_policies=False, 385 ) 386 387 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 388 389 # Here we patch the dummy policy to evaluate to true so the stage is included 390 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 391 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 392 # First request, run the planner 393 response = self.client.get(exec_url) 394 395 self.assertEqual(response.status_code, 200) 396 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 397 398 self.assertEqual(plan.bindings[0], binding) 399 self.assertEqual(plan.bindings[1], binding2) 400 self.assertEqual(plan.bindings[2], binding3) 401 402 self.assertEqual(plan.markers[0].__class__, StageMarker) 403 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 404 self.assertEqual(plan.markers[2].__class__, StageMarker) 405 406 # Second request, this passes the first dummy stage 407 response = self.client.post(exec_url) 408 self.assertEqual(response.status_code, 302) 409 410 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 411 412 self.assertEqual(plan.bindings[0], binding2) 413 self.assertEqual(plan.bindings[1], binding3) 414 415 self.assertEqual(plan.markers[0].__class__, ReevaluateMarker) 416 self.assertEqual(plan.markers[1].__class__, StageMarker) 417 418 # third request, this should trigger the re-evaluate 419 # We do this request without the patch, so the policy results in false 420 response = self.client.post(exec_url) 421 self.assertEqual(response.status_code, 200) 422 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 423 424 def test_reevaluate_keep(self): 425 """Test planner with re-evaluate (everything is kept)""" 426 flow = create_test_flow( 427 FlowDesignation.AUTHENTICATION, 428 ) 429 true_policy = DummyPolicy.objects.create( 430 name=generate_id(), result=True, wait_min=1, wait_max=2 431 ) 432 433 binding = FlowStageBinding.objects.create( 434 target=flow, 435 stage=DummyStage.objects.create(name=generate_id()), 436 order=0, 437 evaluate_on_plan=True, 438 re_evaluate_policies=False, 439 ) 440 binding2 = FlowStageBinding.objects.create( 441 target=flow, 442 stage=DummyStage.objects.create(name=generate_id()), 443 order=1, 444 re_evaluate_policies=True, 445 ) 446 binding3 = FlowStageBinding.objects.create( 447 target=flow, 448 stage=DummyStage.objects.create(name=generate_id()), 449 order=2, 450 evaluate_on_plan=True, 451 re_evaluate_policies=False, 452 ) 453 454 PolicyBinding.objects.create(policy=true_policy, target=binding2, order=0) 455 456 # Here we patch the dummy policy to evaluate to true so the stage is included 457 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 458 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 459 # First request, run the planner 460 response = self.client.get(exec_url) 461 462 self.assertEqual(response.status_code, 200) 463 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 464 465 self.assertEqual(plan.bindings[0], binding) 466 self.assertEqual(plan.bindings[1], binding2) 467 self.assertEqual(plan.bindings[2], binding3) 468 469 self.assertEqual(plan.markers[0].__class__, StageMarker) 470 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 471 self.assertEqual(plan.markers[2].__class__, StageMarker) 472 473 # Second request, this passes the first dummy stage 474 response = self.client.post(exec_url) 475 self.assertEqual(response.status_code, 302) 476 477 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 478 479 self.assertEqual(plan.bindings[0], binding2) 480 self.assertEqual(plan.bindings[1], binding3) 481 482 self.assertEqual(plan.markers[0].__class__, ReevaluateMarker) 483 self.assertEqual(plan.markers[1].__class__, StageMarker) 484 485 # Third request, this passes the first dummy stage 486 response = self.client.post(exec_url) 487 self.assertEqual(response.status_code, 302) 488 489 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 490 491 self.assertEqual(plan.bindings[0], binding3) 492 493 self.assertEqual(plan.markers[0].__class__, StageMarker) 494 495 # third request, this should trigger the re-evaluate 496 # We do this request without the patch, so the policy results in false 497 response = self.client.post(exec_url) 498 self.assertEqual(response.status_code, 200) 499 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 500 501 def test_reevaluate_remove_consecutive(self): 502 """Test planner with re-evaluate (consecutive stages are removed)""" 503 flow = create_test_flow( 504 FlowDesignation.AUTHENTICATION, 505 ) 506 false_policy = DummyPolicy.objects.create( 507 name=generate_id(), result=False, wait_min=1, wait_max=2 508 ) 509 510 binding = FlowStageBinding.objects.create( 511 target=flow, 512 stage=DummyStage.objects.create(name=generate_id()), 513 order=0, 514 evaluate_on_plan=True, 515 re_evaluate_policies=False, 516 ) 517 binding2 = FlowStageBinding.objects.create( 518 target=flow, 519 stage=DummyStage.objects.create(name=generate_id()), 520 order=1, 521 re_evaluate_policies=True, 522 ) 523 binding3 = FlowStageBinding.objects.create( 524 target=flow, 525 stage=DummyStage.objects.create(name=generate_id()), 526 order=2, 527 re_evaluate_policies=True, 528 ) 529 binding4 = FlowStageBinding.objects.create( 530 target=flow, 531 stage=DummyStage.objects.create(name=generate_id()), 532 order=2, 533 evaluate_on_plan=True, 534 re_evaluate_policies=False, 535 ) 536 537 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 538 PolicyBinding.objects.create(policy=false_policy, target=binding3, order=0) 539 540 # Here we patch the dummy policy to evaluate to true so the stage is included 541 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 542 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 543 # First request, run the planner 544 response = self.client.get(exec_url) 545 self.assertEqual(response.status_code, 200) 546 self.assertStageResponse(response, flow, component="ak-stage-dummy") 547 548 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 549 550 self.assertEqual(plan.bindings[0], binding) 551 self.assertEqual(plan.bindings[1], binding2) 552 self.assertEqual(plan.bindings[2], binding3) 553 self.assertEqual(plan.bindings[3], binding4) 554 555 self.assertEqual(plan.markers[0].__class__, StageMarker) 556 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 557 self.assertEqual(plan.markers[2].__class__, ReevaluateMarker) 558 self.assertEqual(plan.markers[3].__class__, StageMarker) 559 560 # Second request, this passes the first dummy stage 561 response = self.client.post(exec_url) 562 self.assertEqual(response.status_code, 302) 563 564 # third request, this should trigger the re-evaluate 565 # A get request will evaluate the policies and this will return stage 4 566 # but it won't save it, hence we can't check the plan 567 response = self.client.get(exec_url) 568 self.assertStageResponse(response, flow, component="ak-stage-dummy") 569 570 # fourth request, this confirms the last stage (dummy4) 571 # We do this request without the patch, so the policy results in false 572 response = self.client.post(exec_url) 573 self.assertEqual(response.status_code, 200) 574 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 575 576 def test_stageview_user_identifier(self): 577 """Test PLAN_CONTEXT_PENDING_USER_IDENTIFIER""" 578 flow = create_test_flow( 579 FlowDesignation.AUTHENTICATION, 580 ) 581 FlowStageBinding.objects.create( 582 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 583 ) 584 585 ident = "test-identifier" 586 587 user = User.objects.create(username="test-user") 588 request = self.request_factory.get( 589 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 590 ) 591 request.user = user 592 planner = FlowPlanner(flow) 593 plan = planner.plan(request, default_context={PLAN_CONTEXT_PENDING_USER_IDENTIFIER: ident}) 594 595 executor = FlowExecutorView() 596 executor.plan = plan 597 executor.flow = flow 598 599 stage_view = StageView(executor) 600 self.assertEqual(ident, stage_view.get_pending_user(for_display=True).username) 601 602 def test_flow_executor_respect_authentication_classes(self): 603 """Test with authentication_classes""" 604 flow = create_test_flow( 605 FlowDesignation.STAGE_CONFIGURATION, 606 authentication=FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED, 607 ) 608 FlowStageBinding.objects.create( 609 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 610 ) 611 612 user = create_test_user() 613 614 def prepare(): 615 request = self.request_factory.get( 616 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 617 ) 618 request.session = {} 619 request.brand = Brand(domain="fallback") 620 621 executor = FlowExecutorView() 622 623 executor.setup(request, flow_slug=flow.slug) 624 625 return request, executor 626 627 # Flow execution should not work in this case, since no user is authenticated, 628 # but authentication is required. 629 with self.subTest("User should not be respected without authentication middleware"): 630 request, executor = prepare() 631 632 executor.authentication_classes = [] 633 634 with patch.object( 635 FlowExecutorView, "handle_invalid_flow", return_value=HttpResponse() 636 ) as handle_invalid_flow: 637 executor.dispatch(request, flow_slug=flow.slug) 638 639 handle_invalid_flow.assert_called_once() 640 641 # Authentication should work in this case, since the user is injected 642 # through a custom authentication class. 643 with self.subTest("User should be respected from authentication middleware"): 644 request, executor = prepare() 645 646 # Inject ConstAuthenticator that always returns 'user' 647 executor.authentication_classes = [const_authenticator_factory(user)] 648 649 with patch.object( 650 FlowExecutorView, "handle_invalid_flow", return_value=HttpResponse() 651 ) as handle_invalid_flow: 652 executor.dispatch(request, flow_slug=flow.slug) 653 654 handle_invalid_flow.assert_not_called() 655 656 def test_invalid_restart(self): 657 """Test flow that restarts on invalid entry""" 658 flow = create_test_flow( 659 FlowDesignation.AUTHENTICATION, 660 ) 661 # Stage 0 is a deny stage that is added dynamically 662 # when the reputation policy says so 663 deny_stage = DenyStage.objects.create(name=generate_id()) 664 reputation_policy = ReputationPolicy.objects.create( 665 name=generate_id(), threshold=-1, check_ip=False 666 ) 667 deny_binding = FlowStageBinding.objects.create( 668 target=flow, 669 stage=deny_stage, 670 order=0, 671 evaluate_on_plan=False, 672 re_evaluate_policies=True, 673 ) 674 PolicyBinding.objects.create(policy=reputation_policy, target=deny_binding, order=0) 675 676 # Stage 1 is an identification stage 677 ident_stage = IdentificationStage.objects.create( 678 name=generate_id(), 679 user_fields=[UserFields.E_MAIL], 680 pretend_user_exists=False, 681 ) 682 FlowStageBinding.objects.create( 683 target=flow, 684 stage=ident_stage, 685 order=1, 686 invalid_response_action=InvalidResponseAction.RESTART_WITH_CONTEXT, 687 ) 688 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 689 # First request, run the planner 690 response = self.client.get(exec_url) 691 self.assertStageResponse( 692 response, 693 flow, 694 component="ak-stage-identification", 695 password_fields=False, 696 primary_action="Log in", 697 sources=[], 698 show_source_labels=False, 699 user_fields=[UserFields.E_MAIL], 700 ) 701 response = self.client.post(exec_url, {"uid_field": "invalid-string"}, follow=True) 702 self.assertStageResponse(response, flow, component="ak-stage-access-denied") 703 704 def test_re_evaluate_group_binding(self): 705 """Test re-evaluate stage binding that has a policy binding to a group""" 706 flow = create_test_flow() 707 708 user_group_membership = create_test_user() 709 user_direct_binding = create_test_user() 710 user_other = create_test_user() 711 712 group_a = Group.objects.create(name=generate_id()) 713 user_group_membership.groups.add(group_a) 714 715 # Stage 0 is an identification stage 716 ident_stage = IdentificationStage.objects.create( 717 name=generate_id(), 718 user_fields=[UserFields.USERNAME], 719 pretend_user_exists=False, 720 ) 721 FlowStageBinding.objects.create( 722 target=flow, 723 stage=ident_stage, 724 order=0, 725 ) 726 727 # Stage 1 is a dummy stage that is only shown for users in group_a 728 dummy_stage = DummyStage.objects.create(name=generate_id()) 729 dummy_binding = FlowStageBinding.objects.create(target=flow, stage=dummy_stage, order=1) 730 PolicyBinding.objects.create(group=group_a, target=dummy_binding, order=0) 731 PolicyBinding.objects.create(user=user_direct_binding, target=dummy_binding, order=0) 732 733 # Stage 2 is a deny stage that (in this case) only user_b will see 734 deny_stage = DenyStage.objects.create(name=generate_id()) 735 FlowStageBinding.objects.create(target=flow, stage=deny_stage, order=2) 736 737 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 738 739 with self.subTest(f"Test user access through group: {user_group_membership}"): 740 self.client.logout() 741 # First request, run the planner 742 response = self.client.get(exec_url) 743 self.assertStageResponse(response, flow, component="ak-stage-identification") 744 response = self.client.post( 745 exec_url, {"uid_field": user_group_membership.username}, follow=True 746 ) 747 self.assertStageResponse(response, flow, component="ak-stage-dummy") 748 with self.subTest(f"Test user access through user: {user_direct_binding}"): 749 self.client.logout() 750 # First request, run the planner 751 response = self.client.get(exec_url) 752 self.assertStageResponse(response, flow, component="ak-stage-identification") 753 response = self.client.post( 754 exec_url, {"uid_field": user_direct_binding.username}, follow=True 755 ) 756 self.assertStageResponse(response, flow, component="ak-stage-dummy") 757 with self.subTest(f"Test user has no access: {user_other}"): 758 self.client.logout() 759 # First request, run the planner 760 response = self.client.get(exec_url) 761 self.assertStageResponse(response, flow, component="ak-stage-identification") 762 response = self.client.post(exec_url, {"uid_field": user_other.username}, follow=True) 763 self.assertStageResponse(response, flow, component="ak-stage-access-denied") 764 765 @patch( 766 "authentik.flows.views.executor.to_stage_response", 767 TO_STAGE_RESPONSE_MOCK, 768 ) 769 def test_invalid_json(self): 770 """Test invalid JSON body""" 771 flow = create_test_flow() 772 FlowStageBinding.objects.create( 773 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 774 ) 775 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 776 777 with override_settings(TEST=False, DEBUG=False): 778 self.client.logout() 779 response = self.client.post(url, data="{", content_type="application/json") 780 self.assertEqual(response.status_code, 200) 781 782 with self.assertRaises(ParseError): 783 self.client.logout() 784 response = self.client.post(url, data="{", content_type="application/json") 785 self.assertEqual(response.status_code, 200) 786 787 def test_cancel_next(self): 788 """Test cancel URL with ?next param set""" 789 flow = create_test_flow() 790 791 # Stage 0 is an identification stage 792 ident_stage = IdentificationStage.objects.create( 793 name=generate_id(), 794 user_fields=[UserFields.USERNAME], 795 ) 796 FlowStageBinding.objects.create( 797 target=flow, 798 stage=ident_stage, 799 order=0, 800 ) 801 802 # Stage 1 is a password stage 803 password_stage = PasswordStage.objects.create(name=generate_id(), backends=[]) 804 FlowStageBinding.objects.create( 805 target=flow, 806 stage=password_stage, 807 order=1, 808 ) 809 res = self.client.get( 810 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 811 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}" 812 ) 813 self.assertStageResponse(res, flow, component="ak-stage-identification") 814 815 res = self.client.post( 816 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 817 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}", 818 data={"component": "ak-stage-identification", "uid_field": generate_id()}, 819 follow=True, 820 ) 821 self.assertEqual(res.status_code, 200) 822 self.assertStageResponse( 823 res, 824 flow, 825 flow_info={ 826 "background": "/static/dist/assets/images/flow_background.jpg", 827 "background_themed_urls": None, 828 "cancel_url": "/flows/-/cancel/?next=%2Ffoo", 829 "layout": "stacked", 830 "title": flow.title, 831 "messages": [], 832 }, 833 ) 834 835 def test_cancel_next_access_denied(self): 836 """Test cancel URL on the access denied page with ?next param set""" 837 flow = create_test_flow() 838 FlowStageBinding.objects.create( 839 target=flow, 840 stage=DenyStage.objects.create(name=generate_id()), 841 order=0, 842 ) 843 res = self.client.get( 844 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 845 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}" 846 ) 847 body = self.assertStageResponse(res, flow, component="ak-stage-access-denied") 848 self.assertEqual(body["flow_info"]["cancel_url"], "/flows/-/cancel/?next=%2Ffoo") 849 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 850 851 res = self.client.get(body["flow_info"]["cancel_url"]) 852 self.assertRedirects(res, "/foo", fetch_redirect_response=False) 853 854 @patch( 855 "authentik.flows.views.executor.to_stage_response", 856 TO_STAGE_RESPONSE_MOCK, 857 ) 858 def test_expired_flow_token(self): 859 """Test that an expired flow token shows an appropriate error message""" 860 flow = create_test_flow( 861 FlowDesignation.RECOVERY, 862 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 863 ) 864 user = create_test_user() 865 plan = FlowPlan(flow_pk=flow.pk.hex, bindings=[], markers=[]) 866 867 token = FlowToken.objects.create( 868 user=user, 869 identifier=generate_id(), 870 flow=flow, 871 _plan=FlowToken.pickle(plan), 872 expires=now() - timedelta(hours=1), 873 ) 874 875 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 876 response = self.client.get( 877 url + f"?{urlencode({QS_QUERY: urlencode({QS_KEY_TOKEN: token.key})})}" 878 ) 879 self.assertStageResponse( 880 response, 881 flow, 882 component="ak-stage-access-denied", 883 error_message="This link is invalid or has expired. Please request a new one.", 884 ) 885 886 @patch( 887 "authentik.flows.views.executor.to_stage_response", 888 TO_STAGE_RESPONSE_MOCK, 889 ) 890 def test_invalid_flow_token_require_token(self): 891 """Test that an invalid/nonexistent token on a REQUIRE_TOKEN flow shows error""" 892 flow = create_test_flow( 893 FlowDesignation.RECOVERY, 894 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 895 ) 896 897 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 898 response = self.client.get( 899 url + f"?{urlencode({QS_QUERY: urlencode({QS_KEY_TOKEN: 'invalid-token'})})}" 900 ) 901 self.assertStageResponse( 902 response, 903 flow, 904 component="ak-stage-access-denied", 905 error_message="This link is invalid or has expired. Please request a new one.", 906 ) 907 908 @patch( 909 "authentik.flows.views.executor.to_stage_response", 910 TO_STAGE_RESPONSE_MOCK, 911 ) 912 def test_no_token_require_token(self): 913 """Test that accessing a REQUIRE_TOKEN flow without any token shows error""" 914 flow = create_test_flow( 915 FlowDesignation.RECOVERY, 916 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 917 ) 918 919 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 920 response = self.client.get(url) 921 self.assertStageResponse( 922 response, 923 flow, 924 component="ak-stage-access-denied", 925 error_message="This link is invalid or has expired. Please request a new one.", 926 )
Test executor
80 @patch( 81 "authentik.flows.views.executor.to_stage_response", 82 TO_STAGE_RESPONSE_MOCK, 83 ) 84 def test_existing_plan_diff_flow(self): 85 """Check that a plan for a different flow cancels the current plan""" 86 flow = create_test_flow( 87 FlowDesignation.AUTHENTICATION, 88 ) 89 stage = DummyStage.objects.create(name=generate_id()) 90 binding = FlowStageBinding(target=flow, stage=stage, order=0) 91 plan = FlowPlan(flow_pk=flow.pk.hex + "a", bindings=[binding], markers=[StageMarker()]) 92 session = self.client.session 93 session[SESSION_KEY_PLAN] = plan 94 session.save() 95 96 cancel_mock = MagicMock() 97 with patch("authentik.flows.views.executor.FlowExecutorView.cancel", cancel_mock): 98 response = self.client.get( 99 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 100 ) 101 self.assertEqual(response.status_code, 302) 102 self.assertEqual(cancel_mock.call_count, 2)
Check that a plan for a different flow cancels the current plan
104 @patch( 105 "authentik.flows.views.executor.to_stage_response", 106 TO_STAGE_RESPONSE_MOCK, 107 ) 108 @patch( 109 "authentik.policies.engine.PolicyEngine.result", 110 POLICY_RETURN_FALSE, 111 ) 112 def test_invalid_non_applicable_flow(self): 113 """Tests that a non-applicable flow returns the correct error message""" 114 flow = create_test_flow( 115 FlowDesignation.AUTHENTICATION, 116 ) 117 118 response = self.client.get( 119 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 120 ) 121 self.assertStageResponse( 122 response, 123 flow=flow, 124 error_message="foo", 125 component="ak-stage-access-denied", 126 )
Tests that a non-applicable flow returns the correct error message
128 @patch( 129 "authentik.flows.views.executor.to_stage_response", 130 TO_STAGE_RESPONSE_MOCK, 131 ) 132 @patch( 133 "authentik.policies.engine.PolicyEngine.result", 134 POLICY_RETURN_FALSE, 135 ) 136 def test_invalid_non_applicable_flow_continue(self): 137 """Tests that a non-applicable flow that should redirect""" 138 flow = create_test_flow( 139 FlowDesignation.AUTHENTICATION, 140 denied_action=FlowDeniedAction.CONTINUE, 141 ) 142 143 response = self.client.get( 144 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 145 ) 146 self.assertEqual(response.status_code, 302) 147 self.assertEqual(response.url, reverse("authentik_core:root-redirect"))
Tests that a non-applicable flow that should redirect
149 @patch( 150 "authentik.flows.views.executor.to_stage_response", 151 TO_STAGE_RESPONSE_MOCK, 152 ) 153 def test_invalid_flow_redirect(self): 154 """Test invalid flow with valid redirect destination""" 155 flow = create_test_flow( 156 FlowDesignation.AUTHENTICATION, 157 ) 158 159 dest = "/unique-string" 160 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 161 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 162 self.assertEqual(response.status_code, 302) 163 self.assertEqual(response.url, "/unique-string")
Test invalid flow with valid redirect destination
165 @patch( 166 "authentik.flows.views.executor.to_stage_response", 167 TO_STAGE_RESPONSE_MOCK, 168 ) 169 def test_invalid_flow_invalid_redirect(self): 170 """Test invalid flow redirect with an invalid URL""" 171 flow = create_test_flow( 172 FlowDesignation.AUTHENTICATION, 173 ) 174 175 dest = "http://something.example.com/unique-string" 176 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 177 178 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 179 self.assertEqual(response.status_code, 200) 180 self.assertStageResponse( 181 response, 182 flow, 183 component="ak-stage-access-denied", 184 error_message="Invalid next URL", 185 )
Test invalid flow redirect with an invalid URL
187 @patch( 188 "authentik.flows.views.executor.to_stage_response", 189 TO_STAGE_RESPONSE_MOCK, 190 ) 191 def test_valid_flow_redirect(self): 192 """Test valid flow with valid redirect destination""" 193 flow = create_test_flow() 194 195 dest = "/unique-string" 196 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 197 198 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 199 self.assertEqual(response.status_code, 302) 200 self.assertEqual(response.url, "/unique-string")
Test valid flow with valid redirect destination
202 def test_flow_done_redirect_challenge_is_final(self): 203 """Test redirects generated when a flow is done are marked as final.""" 204 flow = create_test_flow() 205 206 dest = "/unique-string" 207 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 208 209 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 210 211 self.assertStageResponse( 212 response, 213 component="xak-flow-redirect", 214 to=dest, 215 final_redirect=True, 216 )
Test redirects generated when a flow is done are marked as final.
218 @patch( 219 "authentik.flows.views.executor.to_stage_response", 220 TO_STAGE_RESPONSE_MOCK, 221 ) 222 def test_valid_flow_redirect_authenticated(self): 223 """Test valid flow with valid redirect destination, authenticated already""" 224 flow = create_test_flow() 225 flow.designation = FlowDesignation.AUTHENTICATION 226 flow.authentication = FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED 227 flow.save() 228 self.client.force_login(create_test_user()) 229 230 dest = "/unique-string" 231 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 232 233 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 234 self.assertEqual(response.status_code, 302) 235 self.assertEqual(response.url, "/unique-string")
Test valid flow with valid redirect destination, authenticated already
237 @patch( 238 "authentik.flows.views.executor.to_stage_response", 239 TO_STAGE_RESPONSE_MOCK, 240 ) 241 def test_valid_flow_invalid_redirect(self): 242 """Test valid flow redirect with an invalid URL""" 243 flow = create_test_flow() 244 245 dest = "http://something.example.com/unique-string" 246 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 247 248 response = self.client.get(url + f"?{QS_QUERY}={urlencode({NEXT_ARG_NAME: dest})}") 249 self.assertEqual(response.status_code, 200) 250 self.assertStageResponse( 251 response, 252 flow, 253 component="ak-stage-access-denied", 254 error_message="Invalid next URL", 255 )
Test valid flow redirect with an invalid URL
257 @patch( 258 "authentik.flows.views.executor.to_stage_response", 259 TO_STAGE_RESPONSE_MOCK, 260 ) 261 def test_invalid_empty_flow(self): 262 """Tests that an empty flow returns the correct error message""" 263 flow = create_test_flow( 264 FlowDesignation.AUTHENTICATION, 265 ) 266 267 response = self.client.get( 268 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 269 ) 270 self.assertEqual(response.status_code, 302) 271 self.assertEqual(response.url, reverse("authentik_core:root-redirect"))
Tests that an empty flow returns the correct error message
273 def test_multi_stage_flow(self): 274 """Test a full flow with multiple stages""" 275 flow = create_test_flow( 276 FlowDesignation.AUTHENTICATION, 277 ) 278 FlowStageBinding.objects.create( 279 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 280 ) 281 FlowStageBinding.objects.create( 282 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=1 283 ) 284 285 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 286 # First Request, start planning, renders form 287 response = self.client.get(exec_url) 288 self.assertEqual(response.status_code, 200) 289 # Check that two stages are in plan 290 session = self.client.session 291 plan: FlowPlan = session[SESSION_KEY_PLAN] 292 self.assertEqual(len(plan.bindings), 2) 293 # Second request, submit form, one stage left 294 response = self.client.post(exec_url) 295 # Second request redirects to the same URL 296 self.assertEqual(response.status_code, 302) 297 self.assertEqual(response.url, exec_url) 298 # Check that two stages are in plan 299 session = self.client.session 300 plan: FlowPlan = session[SESSION_KEY_PLAN] 301 self.assertEqual(len(plan.bindings), 1)
Test a full flow with multiple stages
303 @patch( 304 "authentik.flows.views.executor.to_stage_response", 305 TO_STAGE_RESPONSE_MOCK, 306 ) 307 def test_reevaluate_remove_last(self): 308 """Test planner with re-evaluate (last stage is removed)""" 309 flow = create_test_flow( 310 FlowDesignation.AUTHENTICATION, 311 ) 312 false_policy = DummyPolicy.objects.create( 313 name=generate_id(), result=False, wait_min=1, wait_max=2 314 ) 315 316 binding = FlowStageBinding.objects.create( 317 target=flow, 318 stage=DummyStage.objects.create(name=generate_id()), 319 order=0, 320 evaluate_on_plan=True, 321 re_evaluate_policies=False, 322 ) 323 binding2 = FlowStageBinding.objects.create( 324 target=flow, 325 stage=DummyStage.objects.create(name=generate_id()), 326 order=1, 327 re_evaluate_policies=True, 328 ) 329 330 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 331 332 # Here we patch the dummy policy to evaluate to true so the stage is included 333 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 334 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 335 # First request, run the planner 336 response = self.client.get(exec_url) 337 self.assertEqual(response.status_code, 200) 338 339 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 340 341 self.assertEqual(plan.bindings[0], binding) 342 self.assertEqual(plan.bindings[1], binding2) 343 344 self.assertEqual(plan.markers[0].__class__, StageMarker) 345 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 346 347 # Second request, this passes the first dummy stage 348 response = self.client.post(exec_url) 349 self.assertEqual(response.status_code, 302) 350 351 # third request, this should trigger the re-evaluate 352 # We do this request without the patch, so the policy results in false 353 response = self.client.post(exec_url) 354 self.assertEqual(response.status_code, 302) 355 self.assertEqual(response.url, reverse("authentik_core:root-redirect"))
Test planner with re-evaluate (last stage is removed)
357 def test_reevaluate_remove_middle(self): 358 """Test planner with re-evaluate (middle stage is removed)""" 359 flow = create_test_flow( 360 FlowDesignation.AUTHENTICATION, 361 ) 362 false_policy = DummyPolicy.objects.create( 363 name=generate_id(), result=False, wait_min=1, wait_max=2 364 ) 365 366 binding = FlowStageBinding.objects.create( 367 target=flow, 368 stage=DummyStage.objects.create(name=generate_id()), 369 order=0, 370 evaluate_on_plan=True, 371 re_evaluate_policies=False, 372 ) 373 binding2 = FlowStageBinding.objects.create( 374 target=flow, 375 stage=DummyStage.objects.create(name=generate_id()), 376 order=1, 377 re_evaluate_policies=True, 378 ) 379 binding3 = FlowStageBinding.objects.create( 380 target=flow, 381 stage=DummyStage.objects.create(name=generate_id()), 382 order=2, 383 evaluate_on_plan=True, 384 re_evaluate_policies=False, 385 ) 386 387 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 388 389 # Here we patch the dummy policy to evaluate to true so the stage is included 390 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 391 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 392 # First request, run the planner 393 response = self.client.get(exec_url) 394 395 self.assertEqual(response.status_code, 200) 396 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 397 398 self.assertEqual(plan.bindings[0], binding) 399 self.assertEqual(plan.bindings[1], binding2) 400 self.assertEqual(plan.bindings[2], binding3) 401 402 self.assertEqual(plan.markers[0].__class__, StageMarker) 403 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 404 self.assertEqual(plan.markers[2].__class__, StageMarker) 405 406 # Second request, this passes the first dummy stage 407 response = self.client.post(exec_url) 408 self.assertEqual(response.status_code, 302) 409 410 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 411 412 self.assertEqual(plan.bindings[0], binding2) 413 self.assertEqual(plan.bindings[1], binding3) 414 415 self.assertEqual(plan.markers[0].__class__, ReevaluateMarker) 416 self.assertEqual(plan.markers[1].__class__, StageMarker) 417 418 # third request, this should trigger the re-evaluate 419 # We do this request without the patch, so the policy results in false 420 response = self.client.post(exec_url) 421 self.assertEqual(response.status_code, 200) 422 self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
Test planner with re-evaluate (middle stage is removed)
424 def test_reevaluate_keep(self): 425 """Test planner with re-evaluate (everything is kept)""" 426 flow = create_test_flow( 427 FlowDesignation.AUTHENTICATION, 428 ) 429 true_policy = DummyPolicy.objects.create( 430 name=generate_id(), result=True, wait_min=1, wait_max=2 431 ) 432 433 binding = FlowStageBinding.objects.create( 434 target=flow, 435 stage=DummyStage.objects.create(name=generate_id()), 436 order=0, 437 evaluate_on_plan=True, 438 re_evaluate_policies=False, 439 ) 440 binding2 = FlowStageBinding.objects.create( 441 target=flow, 442 stage=DummyStage.objects.create(name=generate_id()), 443 order=1, 444 re_evaluate_policies=True, 445 ) 446 binding3 = FlowStageBinding.objects.create( 447 target=flow, 448 stage=DummyStage.objects.create(name=generate_id()), 449 order=2, 450 evaluate_on_plan=True, 451 re_evaluate_policies=False, 452 ) 453 454 PolicyBinding.objects.create(policy=true_policy, target=binding2, order=0) 455 456 # Here we patch the dummy policy to evaluate to true so the stage is included 457 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 458 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 459 # First request, run the planner 460 response = self.client.get(exec_url) 461 462 self.assertEqual(response.status_code, 200) 463 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 464 465 self.assertEqual(plan.bindings[0], binding) 466 self.assertEqual(plan.bindings[1], binding2) 467 self.assertEqual(plan.bindings[2], binding3) 468 469 self.assertEqual(plan.markers[0].__class__, StageMarker) 470 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 471 self.assertEqual(plan.markers[2].__class__, StageMarker) 472 473 # Second request, this passes the first dummy stage 474 response = self.client.post(exec_url) 475 self.assertEqual(response.status_code, 302) 476 477 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 478 479 self.assertEqual(plan.bindings[0], binding2) 480 self.assertEqual(plan.bindings[1], binding3) 481 482 self.assertEqual(plan.markers[0].__class__, ReevaluateMarker) 483 self.assertEqual(plan.markers[1].__class__, StageMarker) 484 485 # Third request, this passes the first dummy stage 486 response = self.client.post(exec_url) 487 self.assertEqual(response.status_code, 302) 488 489 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 490 491 self.assertEqual(plan.bindings[0], binding3) 492 493 self.assertEqual(plan.markers[0].__class__, StageMarker) 494 495 # third request, this should trigger the re-evaluate 496 # We do this request without the patch, so the policy results in false 497 response = self.client.post(exec_url) 498 self.assertEqual(response.status_code, 200) 499 self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
Test planner with re-evaluate (everything is kept)
501 def test_reevaluate_remove_consecutive(self): 502 """Test planner with re-evaluate (consecutive stages are removed)""" 503 flow = create_test_flow( 504 FlowDesignation.AUTHENTICATION, 505 ) 506 false_policy = DummyPolicy.objects.create( 507 name=generate_id(), result=False, wait_min=1, wait_max=2 508 ) 509 510 binding = FlowStageBinding.objects.create( 511 target=flow, 512 stage=DummyStage.objects.create(name=generate_id()), 513 order=0, 514 evaluate_on_plan=True, 515 re_evaluate_policies=False, 516 ) 517 binding2 = FlowStageBinding.objects.create( 518 target=flow, 519 stage=DummyStage.objects.create(name=generate_id()), 520 order=1, 521 re_evaluate_policies=True, 522 ) 523 binding3 = FlowStageBinding.objects.create( 524 target=flow, 525 stage=DummyStage.objects.create(name=generate_id()), 526 order=2, 527 re_evaluate_policies=True, 528 ) 529 binding4 = FlowStageBinding.objects.create( 530 target=flow, 531 stage=DummyStage.objects.create(name=generate_id()), 532 order=2, 533 evaluate_on_plan=True, 534 re_evaluate_policies=False, 535 ) 536 537 PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0) 538 PolicyBinding.objects.create(policy=false_policy, target=binding3, order=0) 539 540 # Here we patch the dummy policy to evaluate to true so the stage is included 541 with patch("authentik.policies.dummy.models.DummyPolicy.passes", POLICY_RETURN_TRUE): 542 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 543 # First request, run the planner 544 response = self.client.get(exec_url) 545 self.assertEqual(response.status_code, 200) 546 self.assertStageResponse(response, flow, component="ak-stage-dummy") 547 548 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 549 550 self.assertEqual(plan.bindings[0], binding) 551 self.assertEqual(plan.bindings[1], binding2) 552 self.assertEqual(plan.bindings[2], binding3) 553 self.assertEqual(plan.bindings[3], binding4) 554 555 self.assertEqual(plan.markers[0].__class__, StageMarker) 556 self.assertEqual(plan.markers[1].__class__, ReevaluateMarker) 557 self.assertEqual(plan.markers[2].__class__, ReevaluateMarker) 558 self.assertEqual(plan.markers[3].__class__, StageMarker) 559 560 # Second request, this passes the first dummy stage 561 response = self.client.post(exec_url) 562 self.assertEqual(response.status_code, 302) 563 564 # third request, this should trigger the re-evaluate 565 # A get request will evaluate the policies and this will return stage 4 566 # but it won't save it, hence we can't check the plan 567 response = self.client.get(exec_url) 568 self.assertStageResponse(response, flow, component="ak-stage-dummy") 569 570 # fourth request, this confirms the last stage (dummy4) 571 # We do this request without the patch, so the policy results in false 572 response = self.client.post(exec_url) 573 self.assertEqual(response.status_code, 200) 574 self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
Test planner with re-evaluate (consecutive stages are removed)
576 def test_stageview_user_identifier(self): 577 """Test PLAN_CONTEXT_PENDING_USER_IDENTIFIER""" 578 flow = create_test_flow( 579 FlowDesignation.AUTHENTICATION, 580 ) 581 FlowStageBinding.objects.create( 582 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 583 ) 584 585 ident = "test-identifier" 586 587 user = User.objects.create(username="test-user") 588 request = self.request_factory.get( 589 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 590 ) 591 request.user = user 592 planner = FlowPlanner(flow) 593 plan = planner.plan(request, default_context={PLAN_CONTEXT_PENDING_USER_IDENTIFIER: ident}) 594 595 executor = FlowExecutorView() 596 executor.plan = plan 597 executor.flow = flow 598 599 stage_view = StageView(executor) 600 self.assertEqual(ident, stage_view.get_pending_user(for_display=True).username)
Test PLAN_CONTEXT_PENDING_USER_IDENTIFIER
602 def test_flow_executor_respect_authentication_classes(self): 603 """Test with authentication_classes""" 604 flow = create_test_flow( 605 FlowDesignation.STAGE_CONFIGURATION, 606 authentication=FlowAuthenticationRequirement.REQUIRE_AUTHENTICATED, 607 ) 608 FlowStageBinding.objects.create( 609 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 610 ) 611 612 user = create_test_user() 613 614 def prepare(): 615 request = self.request_factory.get( 616 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 617 ) 618 request.session = {} 619 request.brand = Brand(domain="fallback") 620 621 executor = FlowExecutorView() 622 623 executor.setup(request, flow_slug=flow.slug) 624 625 return request, executor 626 627 # Flow execution should not work in this case, since no user is authenticated, 628 # but authentication is required. 629 with self.subTest("User should not be respected without authentication middleware"): 630 request, executor = prepare() 631 632 executor.authentication_classes = [] 633 634 with patch.object( 635 FlowExecutorView, "handle_invalid_flow", return_value=HttpResponse() 636 ) as handle_invalid_flow: 637 executor.dispatch(request, flow_slug=flow.slug) 638 639 handle_invalid_flow.assert_called_once() 640 641 # Authentication should work in this case, since the user is injected 642 # through a custom authentication class. 643 with self.subTest("User should be respected from authentication middleware"): 644 request, executor = prepare() 645 646 # Inject ConstAuthenticator that always returns 'user' 647 executor.authentication_classes = [const_authenticator_factory(user)] 648 649 with patch.object( 650 FlowExecutorView, "handle_invalid_flow", return_value=HttpResponse() 651 ) as handle_invalid_flow: 652 executor.dispatch(request, flow_slug=flow.slug) 653 654 handle_invalid_flow.assert_not_called()
Test with authentication_classes
656 def test_invalid_restart(self): 657 """Test flow that restarts on invalid entry""" 658 flow = create_test_flow( 659 FlowDesignation.AUTHENTICATION, 660 ) 661 # Stage 0 is a deny stage that is added dynamically 662 # when the reputation policy says so 663 deny_stage = DenyStage.objects.create(name=generate_id()) 664 reputation_policy = ReputationPolicy.objects.create( 665 name=generate_id(), threshold=-1, check_ip=False 666 ) 667 deny_binding = FlowStageBinding.objects.create( 668 target=flow, 669 stage=deny_stage, 670 order=0, 671 evaluate_on_plan=False, 672 re_evaluate_policies=True, 673 ) 674 PolicyBinding.objects.create(policy=reputation_policy, target=deny_binding, order=0) 675 676 # Stage 1 is an identification stage 677 ident_stage = IdentificationStage.objects.create( 678 name=generate_id(), 679 user_fields=[UserFields.E_MAIL], 680 pretend_user_exists=False, 681 ) 682 FlowStageBinding.objects.create( 683 target=flow, 684 stage=ident_stage, 685 order=1, 686 invalid_response_action=InvalidResponseAction.RESTART_WITH_CONTEXT, 687 ) 688 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 689 # First request, run the planner 690 response = self.client.get(exec_url) 691 self.assertStageResponse( 692 response, 693 flow, 694 component="ak-stage-identification", 695 password_fields=False, 696 primary_action="Log in", 697 sources=[], 698 show_source_labels=False, 699 user_fields=[UserFields.E_MAIL], 700 ) 701 response = self.client.post(exec_url, {"uid_field": "invalid-string"}, follow=True) 702 self.assertStageResponse(response, flow, component="ak-stage-access-denied")
Test flow that restarts on invalid entry
704 def test_re_evaluate_group_binding(self): 705 """Test re-evaluate stage binding that has a policy binding to a group""" 706 flow = create_test_flow() 707 708 user_group_membership = create_test_user() 709 user_direct_binding = create_test_user() 710 user_other = create_test_user() 711 712 group_a = Group.objects.create(name=generate_id()) 713 user_group_membership.groups.add(group_a) 714 715 # Stage 0 is an identification stage 716 ident_stage = IdentificationStage.objects.create( 717 name=generate_id(), 718 user_fields=[UserFields.USERNAME], 719 pretend_user_exists=False, 720 ) 721 FlowStageBinding.objects.create( 722 target=flow, 723 stage=ident_stage, 724 order=0, 725 ) 726 727 # Stage 1 is a dummy stage that is only shown for users in group_a 728 dummy_stage = DummyStage.objects.create(name=generate_id()) 729 dummy_binding = FlowStageBinding.objects.create(target=flow, stage=dummy_stage, order=1) 730 PolicyBinding.objects.create(group=group_a, target=dummy_binding, order=0) 731 PolicyBinding.objects.create(user=user_direct_binding, target=dummy_binding, order=0) 732 733 # Stage 2 is a deny stage that (in this case) only user_b will see 734 deny_stage = DenyStage.objects.create(name=generate_id()) 735 FlowStageBinding.objects.create(target=flow, stage=deny_stage, order=2) 736 737 exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 738 739 with self.subTest(f"Test user access through group: {user_group_membership}"): 740 self.client.logout() 741 # First request, run the planner 742 response = self.client.get(exec_url) 743 self.assertStageResponse(response, flow, component="ak-stage-identification") 744 response = self.client.post( 745 exec_url, {"uid_field": user_group_membership.username}, follow=True 746 ) 747 self.assertStageResponse(response, flow, component="ak-stage-dummy") 748 with self.subTest(f"Test user access through user: {user_direct_binding}"): 749 self.client.logout() 750 # First request, run the planner 751 response = self.client.get(exec_url) 752 self.assertStageResponse(response, flow, component="ak-stage-identification") 753 response = self.client.post( 754 exec_url, {"uid_field": user_direct_binding.username}, follow=True 755 ) 756 self.assertStageResponse(response, flow, component="ak-stage-dummy") 757 with self.subTest(f"Test user has no access: {user_other}"): 758 self.client.logout() 759 # First request, run the planner 760 response = self.client.get(exec_url) 761 self.assertStageResponse(response, flow, component="ak-stage-identification") 762 response = self.client.post(exec_url, {"uid_field": user_other.username}, follow=True) 763 self.assertStageResponse(response, flow, component="ak-stage-access-denied")
Test re-evaluate stage binding that has a policy binding to a group
765 @patch( 766 "authentik.flows.views.executor.to_stage_response", 767 TO_STAGE_RESPONSE_MOCK, 768 ) 769 def test_invalid_json(self): 770 """Test invalid JSON body""" 771 flow = create_test_flow() 772 FlowStageBinding.objects.create( 773 target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0 774 ) 775 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 776 777 with override_settings(TEST=False, DEBUG=False): 778 self.client.logout() 779 response = self.client.post(url, data="{", content_type="application/json") 780 self.assertEqual(response.status_code, 200) 781 782 with self.assertRaises(ParseError): 783 self.client.logout() 784 response = self.client.post(url, data="{", content_type="application/json") 785 self.assertEqual(response.status_code, 200)
Test invalid JSON body
787 def test_cancel_next(self): 788 """Test cancel URL with ?next param set""" 789 flow = create_test_flow() 790 791 # Stage 0 is an identification stage 792 ident_stage = IdentificationStage.objects.create( 793 name=generate_id(), 794 user_fields=[UserFields.USERNAME], 795 ) 796 FlowStageBinding.objects.create( 797 target=flow, 798 stage=ident_stage, 799 order=0, 800 ) 801 802 # Stage 1 is a password stage 803 password_stage = PasswordStage.objects.create(name=generate_id(), backends=[]) 804 FlowStageBinding.objects.create( 805 target=flow, 806 stage=password_stage, 807 order=1, 808 ) 809 res = self.client.get( 810 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 811 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}" 812 ) 813 self.assertStageResponse(res, flow, component="ak-stage-identification") 814 815 res = self.client.post( 816 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 817 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}", 818 data={"component": "ak-stage-identification", "uid_field": generate_id()}, 819 follow=True, 820 ) 821 self.assertEqual(res.status_code, 200) 822 self.assertStageResponse( 823 res, 824 flow, 825 flow_info={ 826 "background": "/static/dist/assets/images/flow_background.jpg", 827 "background_themed_urls": None, 828 "cancel_url": "/flows/-/cancel/?next=%2Ffoo", 829 "layout": "stacked", 830 "title": flow.title, 831 "messages": [], 832 }, 833 )
Test cancel URL with ?next param set
835 def test_cancel_next_access_denied(self): 836 """Test cancel URL on the access denied page with ?next param set""" 837 flow = create_test_flow() 838 FlowStageBinding.objects.create( 839 target=flow, 840 stage=DenyStage.objects.create(name=generate_id()), 841 order=0, 842 ) 843 res = self.client.get( 844 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 845 + f"?{urlencode({QS_QUERY: urlencode({NEXT_ARG_NAME: "/foo"})})}" 846 ) 847 body = self.assertStageResponse(res, flow, component="ak-stage-access-denied") 848 self.assertEqual(body["flow_info"]["cancel_url"], "/flows/-/cancel/?next=%2Ffoo") 849 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 850 851 res = self.client.get(body["flow_info"]["cancel_url"]) 852 self.assertRedirects(res, "/foo", fetch_redirect_response=False)
Test cancel URL on the access denied page with ?next param set
854 @patch( 855 "authentik.flows.views.executor.to_stage_response", 856 TO_STAGE_RESPONSE_MOCK, 857 ) 858 def test_expired_flow_token(self): 859 """Test that an expired flow token shows an appropriate error message""" 860 flow = create_test_flow( 861 FlowDesignation.RECOVERY, 862 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 863 ) 864 user = create_test_user() 865 plan = FlowPlan(flow_pk=flow.pk.hex, bindings=[], markers=[]) 866 867 token = FlowToken.objects.create( 868 user=user, 869 identifier=generate_id(), 870 flow=flow, 871 _plan=FlowToken.pickle(plan), 872 expires=now() - timedelta(hours=1), 873 ) 874 875 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 876 response = self.client.get( 877 url + f"?{urlencode({QS_QUERY: urlencode({QS_KEY_TOKEN: token.key})})}" 878 ) 879 self.assertStageResponse( 880 response, 881 flow, 882 component="ak-stage-access-denied", 883 error_message="This link is invalid or has expired. Please request a new one.", 884 )
Test that an expired flow token shows an appropriate error message
886 @patch( 887 "authentik.flows.views.executor.to_stage_response", 888 TO_STAGE_RESPONSE_MOCK, 889 ) 890 def test_invalid_flow_token_require_token(self): 891 """Test that an invalid/nonexistent token on a REQUIRE_TOKEN flow shows error""" 892 flow = create_test_flow( 893 FlowDesignation.RECOVERY, 894 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 895 ) 896 897 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 898 response = self.client.get( 899 url + f"?{urlencode({QS_QUERY: urlencode({QS_KEY_TOKEN: 'invalid-token'})})}" 900 ) 901 self.assertStageResponse( 902 response, 903 flow, 904 component="ak-stage-access-denied", 905 error_message="This link is invalid or has expired. Please request a new one.", 906 )
Test that an invalid/nonexistent token on a REQUIRE_TOKEN flow shows error
908 @patch( 909 "authentik.flows.views.executor.to_stage_response", 910 TO_STAGE_RESPONSE_MOCK, 911 ) 912 def test_no_token_require_token(self): 913 """Test that accessing a REQUIRE_TOKEN flow without any token shows error""" 914 flow = create_test_flow( 915 FlowDesignation.RECOVERY, 916 authentication=FlowAuthenticationRequirement.REQUIRE_TOKEN, 917 ) 918 919 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 920 response = self.client.get(url) 921 self.assertStageResponse( 922 response, 923 flow, 924 component="ak-stage-access-denied", 925 error_message="This link is invalid or has expired. Please request a new one.", 926 )
Test that accessing a REQUIRE_TOKEN flow without any token shows error