authentik.enterprise.lifecycle.offboarding.tests.test_offboarding
1import time 2from datetime import timedelta 3from threading import Event as ThreadEvent 4from threading import Thread 5from unittest.mock import patch 6 7from django.apps import apps 8from django.db import connection 9from django.test import TransactionTestCase 10from django.urls import reverse 11from django.utils.timezone import now 12from rest_framework.test import APITestCase 13 14from authentik.core.models import ( 15 AuthenticatedSession, 16 Session, 17 Token, 18 TokenIntents, 19 User, 20 UserTypes, 21) 22from authentik.core.tests.utils import create_test_admin_user, create_test_user 23from authentik.enterprise.lifecycle.offboarding.actions import offboard_user 24from authentik.enterprise.lifecycle.offboarding.api import UserOffboardingSerializer 25from authentik.enterprise.lifecycle.offboarding.models import ( 26 OffboardingAction, 27 OffboardingStatus, 28 UserOffboarding, 29) 30from authentik.enterprise.lifecycle.offboarding.tasks import ( 31 MAX_OFFBOARDING_ATTEMPTS, 32 execute_due_offboardings, 33 execute_offboarding, 34) 35from authentik.enterprise.tests import enterprise_test 36from authentik.events.models import Event, EventAction 37from authentik.lib.generators import generate_id 38 39 40def _add_session(user: User) -> AuthenticatedSession: 41 session = Session.objects.create( 42 session_key=generate_id(), last_ip="255.255.255.255", last_user_agent="" 43 ) 44 return AuthenticatedSession.objects.create(session=session, user=user) 45 46 47def _add_token(user: User) -> Token: 48 return Token.objects.create(identifier=generate_id(), user=user, intent=TokenIntents.INTENT_API) 49 50 51class TestOffboardingService(APITestCase): 52 def setUp(self): 53 self.user = create_test_user() 54 55 def test_deactivate_revokes_access(self): 56 _add_session(self.user) 57 _add_token(self.user) 58 offboard_user(self.user, OffboardingAction.DEACTIVATE) 59 self.user.refresh_from_db() 60 self.assertFalse(self.user.is_active) 61 self.assertFalse(AuthenticatedSession.objects.filter(user=self.user).exists()) 62 self.assertFalse(Token.objects.filter(user=self.user).exists()) 63 64 def test_delete_removes_user(self): 65 pk = self.user.pk 66 offboard_user(self.user, OffboardingAction.DELETE) 67 self.assertFalse(User.objects.filter(pk=pk).exists()) 68 69 def test_revoke_toggles_off(self): 70 _add_session(self.user) 71 _add_token(self.user) 72 offboard_user( 73 self.user, 74 OffboardingAction.DEACTIVATE, 75 revoke_sessions=False, 76 revoke_tokens=False, 77 ) 78 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 79 self.assertTrue(Token.objects.filter(user=self.user).exists()) 80 81 def test_revoke_sessions_only(self): 82 """Sessions and tokens toggle independently: sessions on, tokens off.""" 83 _add_session(self.user) 84 _add_token(self.user) 85 offboard_user( 86 self.user, 87 OffboardingAction.DEACTIVATE, 88 revoke_sessions=True, 89 revoke_tokens=False, 90 ) 91 self.assertFalse(AuthenticatedSession.objects.filter(user=self.user).exists()) 92 self.assertTrue(Token.objects.filter(user=self.user).exists()) 93 94 def test_revoke_tokens_only(self): 95 """Sessions and tokens toggle independently: tokens on, sessions off.""" 96 _add_session(self.user) 97 _add_token(self.user) 98 offboard_user( 99 self.user, 100 OffboardingAction.DEACTIVATE, 101 revoke_sessions=False, 102 revoke_tokens=True, 103 ) 104 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 105 self.assertFalse(Token.objects.filter(user=self.user).exists()) 106 107 108class TestOffboardingSweeper(APITestCase): 109 @classmethod 110 def setUpTestData(cls): 111 config = apps.get_app_config("authentik_tasks_schedules") 112 config._on_startup_callback(None) 113 114 def setUp(self): 115 self.user = create_test_user() 116 117 def test_due_offboarding_dispatched_under_schedule(self): 118 """The sweeper dispatches each due offboarding.""" 119 UserOffboarding.objects.create( 120 user=self.user, 121 scheduled_at=now() - timedelta(minutes=1), 122 action=OffboardingAction.DEACTIVATE, 123 ) 124 with patch( 125 "authentik.enterprise.lifecycle.offboarding.tasks.execute_offboarding.send_with_options" 126 ) as send: 127 # Dispatch through the worker so CurrentTask (and its rel_obj) is populated. 128 execute_due_offboardings.send() 129 send.assert_called_once() 130 131 def test_due_offboarding_executed(self): 132 offboarding = UserOffboarding.objects.create( 133 user=self.user, 134 scheduled_at=now() - timedelta(minutes=1), 135 action=OffboardingAction.DEACTIVATE, 136 ) 137 execute_offboarding(str(offboarding.pk)) 138 offboarding.refresh_from_db() 139 self.user.refresh_from_db() 140 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 141 self.assertIsNotNone(offboarding.executed_at) 142 self.assertFalse(self.user.is_active) 143 144 def test_audit_event_attributed_to_initiator(self): 145 """The audit event names the admin who scheduled it, not the offboarded user.""" 146 admin = create_test_admin_user() 147 offboarding = UserOffboarding.objects.create( 148 user=self.user, 149 scheduled_at=now() - timedelta(minutes=1), 150 action=OffboardingAction.DEACTIVATE, 151 created_by=admin, 152 ) 153 execute_offboarding(str(offboarding.pk)) 154 event = Event.objects.filter(action=EventAction.USER_OFFBOARDED).latest("created") 155 self.assertEqual(event.user.get("pk"), admin.pk) 156 self.assertNotEqual(event.user.get("pk"), self.user.pk) 157 self.assertEqual(event.context.get("user_pk"), self.user.pk) 158 159 def test_failed_execution_is_atomic_and_retryable(self): 160 """A mid-way failure rolls back every change and leaves the row retryable.""" 161 _add_session(self.user) 162 _add_token(self.user) 163 offboarding = UserOffboarding.objects.create( 164 user=self.user, 165 scheduled_at=now() - timedelta(minutes=1), 166 action=OffboardingAction.DEACTIVATE, 167 ) 168 # Sessions/tokens are revoked before the audit event is built; make the 169 # event raise so the failure lands mid-offboarding. 170 with patch( 171 "authentik.enterprise.lifecycle.offboarding.actions.Event.new", 172 side_effect=RuntimeError("boom"), 173 ): 174 with self.assertRaises(RuntimeError): 175 execute_offboarding(str(offboarding.pk)) 176 177 offboarding.refresh_from_db() 178 self.user.refresh_from_db() 179 # Nothing was applied: user still active, sessions/tokens intact. 180 self.assertTrue(self.user.is_active) 181 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 182 self.assertTrue(Token.objects.filter(user=self.user).exists()) 183 # Still retryable, with the failed attempt recorded. 184 self.assertEqual(offboarding.status, OffboardingStatus.PENDING) 185 self.assertEqual(offboarding.attempts, 1) 186 187 def test_offboarding_marked_failed_after_max_attempts(self): 188 """A persistently failing offboarding goes terminal without touching the user.""" 189 offboarding = UserOffboarding.objects.create( 190 user=self.user, 191 scheduled_at=now() - timedelta(minutes=1), 192 action=OffboardingAction.DEACTIVATE, 193 ) 194 with patch( 195 "authentik.enterprise.lifecycle.offboarding.actions.Event.new", 196 side_effect=RuntimeError("boom"), 197 ): 198 for _ in range(MAX_OFFBOARDING_ATTEMPTS): 199 with self.assertRaises(RuntimeError): 200 execute_offboarding(str(offboarding.pk)) 201 202 offboarding.refresh_from_db() 203 self.user.refresh_from_db() 204 self.assertEqual(offboarding.status, OffboardingStatus.FAILED) 205 self.assertEqual(offboarding.attempts, MAX_OFFBOARDING_ATTEMPTS) 206 self.assertTrue(self.user.is_active) 207 208 def test_redispatch_of_completed_offboarding_is_noop(self): 209 """Re-dispatching an already-executed offboarding does not run it again.""" 210 offboarding = UserOffboarding.objects.create( 211 user=self.user, 212 scheduled_at=now() - timedelta(minutes=1), 213 action=OffboardingAction.DEACTIVATE, 214 ) 215 execute_offboarding(str(offboarding.pk)) 216 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1) 217 # The sweeper may re-queue the same row; the status guard must no-op. 218 execute_offboarding(str(offboarding.pk)) 219 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1) 220 221 def test_future_offboarding_not_picked_up(self): 222 offboarding = UserOffboarding.objects.create( 223 user=self.user, 224 scheduled_at=now() + timedelta(days=1), 225 action=OffboardingAction.DEACTIVATE, 226 ) 227 execute_due_offboardings.send() 228 offboarding.refresh_from_db() 229 self.user.refresh_from_db() 230 self.assertEqual(offboarding.status, OffboardingStatus.PENDING) 231 self.assertTrue(self.user.is_active) 232 233 234class TestOffboardingConcurrency(TransactionTestCase): 235 """Two workers must not offboard the same user twice.""" 236 237 def setUp(self): 238 self.user = create_test_user() 239 240 def test_concurrent_dispatch_executes_once(self): 241 offboarding = UserOffboarding.objects.create( 242 user=self.user, 243 scheduled_at=now() - timedelta(minutes=1), 244 action=OffboardingAction.DEACTIVATE, 245 ) 246 pk = str(offboarding.pk) 247 248 inside_lock = ThreadEvent() # set once a worker holds the row lock 249 may_finish = ThreadEvent() # released once the other worker is running 250 errors: list = [] 251 real_offboard = offboard_user 252 253 def slow_offboard(*args, **kwargs): 254 # The worker that reaches this holds the row lock; hold it briefly so 255 # the other worker is forced to contend for the same PENDING row. 256 inside_lock.set() 257 may_finish.wait(timeout=10) 258 return real_offboard(*args, **kwargs) 259 260 class Worker(Thread): 261 __test__ = False 262 263 def run(self): 264 try: 265 execute_offboarding(pk) 266 except Exception as exc: # noqa: BLE001 267 errors.append(exc) 268 finally: 269 connection.close() 270 271 with patch( 272 "authentik.enterprise.lifecycle.offboarding.actions.offboard_user", 273 side_effect=slow_offboard, 274 ): 275 first = Worker() 276 first.start() 277 self.assertTrue(inside_lock.wait(timeout=10), "worker never acquired the lock") 278 # First worker now holds the lock inside slow_offboard. The second must 279 # block on select_for_update; give it a moment to reach the lock, then 280 # let the first finish. (The single-execution invariant holds for every 281 # interleaving, since the first worker locks the row before the second starts.) 282 second = Worker() 283 second.start() 284 time.sleep(0.5) 285 may_finish.set() 286 first.join(timeout=15) 287 second.join(timeout=15) 288 289 self.assertEqual(errors, []) 290 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1) 291 offboarding.refresh_from_db() 292 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 293 self.user.refresh_from_db() 294 self.assertFalse(self.user.is_active) 295 296 def test_cancel_racing_execution_does_not_clobber(self): 297 """A cancel that loses the race to a running execution must not overwrite it.""" 298 offboarding = UserOffboarding.objects.create( 299 user=self.user, 300 scheduled_at=now() - timedelta(minutes=1), 301 action=OffboardingAction.DEACTIVATE, 302 ) 303 pk = str(offboarding.pk) 304 305 inside_lock = ThreadEvent() # set once the worker holds the row lock 306 may_finish = ThreadEvent() # released once the canceller is contending 307 errors: list = [] 308 cancelled: list = [] 309 real_offboard = offboard_user 310 311 def slow_offboard(*args, **kwargs): 312 inside_lock.set() 313 may_finish.wait(timeout=10) 314 return real_offboard(*args, **kwargs) 315 316 class Worker(Thread): 317 __test__ = False 318 319 def run(self): 320 try: 321 execute_offboarding(pk) 322 except Exception as exc: # noqa: BLE001 323 errors.append(exc) 324 finally: 325 connection.close() 326 327 class Canceller(Thread): 328 __test__ = False 329 330 def run(self): 331 try: 332 cancelled.append(UserOffboarding.objects.get(pk=pk).cancel()) 333 except Exception as exc: # noqa: BLE001 334 errors.append(exc) 335 finally: 336 connection.close() 337 338 with patch( 339 "authentik.enterprise.lifecycle.offboarding.actions.offboard_user", 340 side_effect=slow_offboard, 341 ): 342 worker = Worker() 343 worker.start() 344 self.assertTrue(inside_lock.wait(timeout=10), "worker never acquired the lock") 345 # Worker holds the lock mid-execution; the cancel must block on it, 346 # then observe COMPLETED and refuse instead of clobbering the status. 347 canceller = Canceller() 348 canceller.start() 349 time.sleep(0.5) 350 may_finish.set() 351 worker.join(timeout=15) 352 canceller.join(timeout=15) 353 354 self.assertEqual(errors, []) 355 self.assertEqual(cancelled, [False]) 356 offboarding.refresh_from_db() 357 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 358 self.user.refresh_from_db() 359 self.assertFalse(self.user.is_active) 360 361 362@enterprise_test() 363class TestOffboardingAPI(APITestCase): 364 def setUp(self): 365 self.admin = create_test_admin_user() 366 self.client.force_login(self.admin) 367 self.user = create_test_user() 368 369 @classmethod 370 def setUpTestData(cls): 371 config = apps.get_app_config("authentik_tasks_schedules") 372 config._on_startup_callback(None) 373 374 def test_create(self): 375 response = self.client.post( 376 reverse("authentik_api:useroffboarding-list"), 377 { 378 "user": self.user.pk, 379 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 380 "action": OffboardingAction.DELETE, 381 }, 382 ) 383 self.assertEqual(response.status_code, 201) 384 self.assertEqual(response.data["status"], OffboardingStatus.PENDING) 385 offboarding = UserOffboarding.objects.get(pk=response.data["id"]) 386 self.assertEqual(offboarding.created_by, self.admin) 387 388 def test_create_in_past_rejected(self): 389 response = self.client.post( 390 reverse("authentik_api:useroffboarding-list"), 391 { 392 "user": self.user.pk, 393 "scheduled_at": (now() - timedelta(days=1)).isoformat(), 394 "action": OffboardingAction.DEACTIVATE, 395 }, 396 ) 397 self.assertEqual(response.status_code, 400) 398 self.assertIn("scheduled_at", response.data) 399 400 def test_duplicate_pending_rejected(self): 401 UserOffboarding.objects.create( 402 user=self.user, 403 scheduled_at=now() + timedelta(days=1), 404 action=OffboardingAction.DEACTIVATE, 405 ) 406 response = self.client.post( 407 reverse("authentik_api:useroffboarding-list"), 408 { 409 "user": self.user.pk, 410 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 411 "action": OffboardingAction.DEACTIVATE, 412 }, 413 ) 414 self.assertEqual(response.status_code, 400) 415 self.assertJSONEqual( 416 response.content, 417 {"non_field_errors": ["The fields user must make a unique set."]}, 418 ) 419 420 def test_duplicate_pending_race_returns_400(self): 421 """If two requests race past validation, the DB constraint yields a 400, not a 500.""" 422 UserOffboarding.objects.create( 423 user=self.user, 424 scheduled_at=now() + timedelta(days=1), 425 action=OffboardingAction.DEACTIVATE, 426 ) 427 # Simulate the Time-of-Check to Time-of-Use: bypass the duplicate pre-check so the 428 # insert is the first place the conflict is detected (the partial unique constraint). 429 with patch.object(UserOffboardingSerializer, "validate", new=lambda self, attrs: attrs): 430 response = self.client.post( 431 reverse("authentik_api:useroffboarding-list"), 432 { 433 "user": self.user.pk, 434 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 435 "action": OffboardingAction.DEACTIVATE, 436 }, 437 ) 438 self.assertEqual(response.status_code, 400) 439 self.assertJSONEqual( 440 response.content, 441 {"non_field_errors": ["The fields user must make a unique set."]}, 442 ) # The losing insert did not create a second pending row. 443 self.assertEqual( 444 UserOffboarding.objects.filter( 445 user=self.user, status=OffboardingStatus.PENDING 446 ).count(), 447 1, 448 ) 449 450 def test_offboard_self_rejected(self): 451 response = self.client.post( 452 reverse("authentik_api:useroffboarding-list"), 453 { 454 "user": self.admin.pk, 455 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 456 "action": OffboardingAction.DEACTIVATE, 457 }, 458 ) 459 self.assertEqual(response.status_code, 400) 460 self.assertIn("user", response.data) 461 462 def test_offboard_internal_service_account_rejected(self): 463 service_account = User.objects.create( 464 username=generate_id(), type=UserTypes.INTERNAL_SERVICE_ACCOUNT 465 ) 466 response = self.client.post( 467 reverse("authentik_api:useroffboarding-list"), 468 { 469 "user": service_account.pk, 470 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 471 "action": OffboardingAction.DEACTIVATE, 472 }, 473 ) 474 self.assertEqual(response.status_code, 400) 475 self.assertIn("user", response.data) 476 477 def test_cancel(self): 478 offboarding = UserOffboarding.objects.create( 479 user=self.user, 480 scheduled_at=now() + timedelta(days=1), 481 action=OffboardingAction.DEACTIVATE, 482 ) 483 response = self.client.delete( 484 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 485 ) 486 self.assertEqual(response.status_code, 204) 487 # The row is retained as an audit record, transitioned to CANCELED. 488 offboarding.refresh_from_db() 489 self.assertEqual(offboarding.status, OffboardingStatus.CANCELED) 490 self.assertIsNotNone(offboarding.executed_at) 491 492 def test_cancel_frees_user_for_rescheduling(self): 493 """A cancelled offboarding no longer blocks the unique-pending constraint.""" 494 offboarding = UserOffboarding.objects.create( 495 user=self.user, 496 scheduled_at=now() + timedelta(days=1), 497 action=OffboardingAction.DEACTIVATE, 498 ) 499 offboarding.cancel() 500 response = self.client.post( 501 reverse("authentik_api:useroffboarding-list"), 502 { 503 "user": self.user.pk, 504 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 505 "action": OffboardingAction.DEACTIVATE, 506 }, 507 ) 508 self.assertEqual(response.status_code, 201) 509 510 def test_cancel_non_pending_rejected(self): 511 offboarding = UserOffboarding.objects.create( 512 user=self.user, 513 scheduled_at=now() + timedelta(days=1), 514 action=OffboardingAction.DEACTIVATE, 515 status=OffboardingStatus.COMPLETED, 516 ) 517 response = self.client.delete( 518 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 519 ) 520 self.assertEqual(response.status_code, 400) 521 offboarding.refresh_from_db() 522 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 523 524 def test_cancel_own_offboarding_rejected(self): 525 """Separation of duties: you cannot cancel an offboarding that targets you.""" 526 offboarding = UserOffboarding.objects.create( 527 user=self.admin, 528 scheduled_at=now() + timedelta(days=1), 529 action=OffboardingAction.DEACTIVATE, 530 ) 531 response = self.client.delete( 532 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 533 ) 534 self.assertEqual(response.status_code, 403) 535 offboarding.refresh_from_db() 536 self.assertEqual(offboarding.status, OffboardingStatus.PENDING) 537 538 def test_update_not_allowed(self): 539 """Records are immutable: PUT/PATCH must not rewrite an offboarding.""" 540 offboarding = UserOffboarding.objects.create( 541 user=self.user, 542 scheduled_at=now() + timedelta(days=1), 543 action=OffboardingAction.DEACTIVATE, 544 ) 545 url = reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 546 for method in (self.client.put, self.client.patch): 547 response = method(url, {"action": OffboardingAction.DELETE}) 548 self.assertEqual(response.status_code, 405) 549 offboarding.refresh_from_db() 550 self.assertEqual(offboarding.action, OffboardingAction.DEACTIVATE) 551 552 def test_generated_filter_keeps_rows_of_deleted_rules(self): 553 from authentik.enterprise.lifecycle.expiration.models import UserExpirationRule 554 555 with patch( 556 "authentik.enterprise.lifecycle.expiration.tasks.apply_expiration_rule.send_with_options" 557 ): 558 rule = UserExpirationRule.objects.create(name=generate_id()) 559 generated = UserOffboarding.objects.create( 560 user=create_test_user(), 561 rule=rule, 562 generated=True, 563 scheduled_at=now(), 564 status=OffboardingStatus.COMPLETED, 565 ) 566 manual = UserOffboarding.objects.create(user=self.user, scheduled_at=now()) 567 rule.delete() 568 url = reverse("authentik_api:useroffboarding-list") 569 for value, expected in (("true", generated), ("false", manual)): 570 with self.subTest(generated=value): 571 response = self.client.get(url, {"generated": value}) 572 self.assertEqual(response.status_code, 200) 573 results = response.json()["results"] 574 self.assertEqual([row["id"] for row in results], [str(expected.pk)]) 575 self.assertEqual(results[0]["generated"], value == "true") 576 self.assertIsNone(results[0]["rule"])
52class TestOffboardingService(APITestCase): 53 def setUp(self): 54 self.user = create_test_user() 55 56 def test_deactivate_revokes_access(self): 57 _add_session(self.user) 58 _add_token(self.user) 59 offboard_user(self.user, OffboardingAction.DEACTIVATE) 60 self.user.refresh_from_db() 61 self.assertFalse(self.user.is_active) 62 self.assertFalse(AuthenticatedSession.objects.filter(user=self.user).exists()) 63 self.assertFalse(Token.objects.filter(user=self.user).exists()) 64 65 def test_delete_removes_user(self): 66 pk = self.user.pk 67 offboard_user(self.user, OffboardingAction.DELETE) 68 self.assertFalse(User.objects.filter(pk=pk).exists()) 69 70 def test_revoke_toggles_off(self): 71 _add_session(self.user) 72 _add_token(self.user) 73 offboard_user( 74 self.user, 75 OffboardingAction.DEACTIVATE, 76 revoke_sessions=False, 77 revoke_tokens=False, 78 ) 79 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 80 self.assertTrue(Token.objects.filter(user=self.user).exists()) 81 82 def test_revoke_sessions_only(self): 83 """Sessions and tokens toggle independently: sessions on, tokens off.""" 84 _add_session(self.user) 85 _add_token(self.user) 86 offboard_user( 87 self.user, 88 OffboardingAction.DEACTIVATE, 89 revoke_sessions=True, 90 revoke_tokens=False, 91 ) 92 self.assertFalse(AuthenticatedSession.objects.filter(user=self.user).exists()) 93 self.assertTrue(Token.objects.filter(user=self.user).exists()) 94 95 def test_revoke_tokens_only(self): 96 """Sessions and tokens toggle independently: tokens on, sessions off.""" 97 _add_session(self.user) 98 _add_token(self.user) 99 offboard_user( 100 self.user, 101 OffboardingAction.DEACTIVATE, 102 revoke_sessions=False, 103 revoke_tokens=True, 104 ) 105 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 106 self.assertFalse(Token.objects.filter(user=self.user).exists())
Similar to TransactionTestCase, but use transaction.atomic() to achieve
test isolation.
In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior).
On database backends with no transaction support, TestCase behaves as TransactionTestCase.
56 def test_deactivate_revokes_access(self): 57 _add_session(self.user) 58 _add_token(self.user) 59 offboard_user(self.user, OffboardingAction.DEACTIVATE) 60 self.user.refresh_from_db() 61 self.assertFalse(self.user.is_active) 62 self.assertFalse(AuthenticatedSession.objects.filter(user=self.user).exists()) 63 self.assertFalse(Token.objects.filter(user=self.user).exists())
70 def test_revoke_toggles_off(self): 71 _add_session(self.user) 72 _add_token(self.user) 73 offboard_user( 74 self.user, 75 OffboardingAction.DEACTIVATE, 76 revoke_sessions=False, 77 revoke_tokens=False, 78 ) 79 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 80 self.assertTrue(Token.objects.filter(user=self.user).exists())
82 def test_revoke_sessions_only(self): 83 """Sessions and tokens toggle independently: sessions on, tokens off.""" 84 _add_session(self.user) 85 _add_token(self.user) 86 offboard_user( 87 self.user, 88 OffboardingAction.DEACTIVATE, 89 revoke_sessions=True, 90 revoke_tokens=False, 91 ) 92 self.assertFalse(AuthenticatedSession.objects.filter(user=self.user).exists()) 93 self.assertTrue(Token.objects.filter(user=self.user).exists())
Sessions and tokens toggle independently: sessions on, tokens off.
95 def test_revoke_tokens_only(self): 96 """Sessions and tokens toggle independently: tokens on, sessions off.""" 97 _add_session(self.user) 98 _add_token(self.user) 99 offboard_user( 100 self.user, 101 OffboardingAction.DEACTIVATE, 102 revoke_sessions=False, 103 revoke_tokens=True, 104 ) 105 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 106 self.assertFalse(Token.objects.filter(user=self.user).exists())
Sessions and tokens toggle independently: tokens on, sessions off.
109class TestOffboardingSweeper(APITestCase): 110 @classmethod 111 def setUpTestData(cls): 112 config = apps.get_app_config("authentik_tasks_schedules") 113 config._on_startup_callback(None) 114 115 def setUp(self): 116 self.user = create_test_user() 117 118 def test_due_offboarding_dispatched_under_schedule(self): 119 """The sweeper dispatches each due offboarding.""" 120 UserOffboarding.objects.create( 121 user=self.user, 122 scheduled_at=now() - timedelta(minutes=1), 123 action=OffboardingAction.DEACTIVATE, 124 ) 125 with patch( 126 "authentik.enterprise.lifecycle.offboarding.tasks.execute_offboarding.send_with_options" 127 ) as send: 128 # Dispatch through the worker so CurrentTask (and its rel_obj) is populated. 129 execute_due_offboardings.send() 130 send.assert_called_once() 131 132 def test_due_offboarding_executed(self): 133 offboarding = UserOffboarding.objects.create( 134 user=self.user, 135 scheduled_at=now() - timedelta(minutes=1), 136 action=OffboardingAction.DEACTIVATE, 137 ) 138 execute_offboarding(str(offboarding.pk)) 139 offboarding.refresh_from_db() 140 self.user.refresh_from_db() 141 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 142 self.assertIsNotNone(offboarding.executed_at) 143 self.assertFalse(self.user.is_active) 144 145 def test_audit_event_attributed_to_initiator(self): 146 """The audit event names the admin who scheduled it, not the offboarded user.""" 147 admin = create_test_admin_user() 148 offboarding = UserOffboarding.objects.create( 149 user=self.user, 150 scheduled_at=now() - timedelta(minutes=1), 151 action=OffboardingAction.DEACTIVATE, 152 created_by=admin, 153 ) 154 execute_offboarding(str(offboarding.pk)) 155 event = Event.objects.filter(action=EventAction.USER_OFFBOARDED).latest("created") 156 self.assertEqual(event.user.get("pk"), admin.pk) 157 self.assertNotEqual(event.user.get("pk"), self.user.pk) 158 self.assertEqual(event.context.get("user_pk"), self.user.pk) 159 160 def test_failed_execution_is_atomic_and_retryable(self): 161 """A mid-way failure rolls back every change and leaves the row retryable.""" 162 _add_session(self.user) 163 _add_token(self.user) 164 offboarding = UserOffboarding.objects.create( 165 user=self.user, 166 scheduled_at=now() - timedelta(minutes=1), 167 action=OffboardingAction.DEACTIVATE, 168 ) 169 # Sessions/tokens are revoked before the audit event is built; make the 170 # event raise so the failure lands mid-offboarding. 171 with patch( 172 "authentik.enterprise.lifecycle.offboarding.actions.Event.new", 173 side_effect=RuntimeError("boom"), 174 ): 175 with self.assertRaises(RuntimeError): 176 execute_offboarding(str(offboarding.pk)) 177 178 offboarding.refresh_from_db() 179 self.user.refresh_from_db() 180 # Nothing was applied: user still active, sessions/tokens intact. 181 self.assertTrue(self.user.is_active) 182 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 183 self.assertTrue(Token.objects.filter(user=self.user).exists()) 184 # Still retryable, with the failed attempt recorded. 185 self.assertEqual(offboarding.status, OffboardingStatus.PENDING) 186 self.assertEqual(offboarding.attempts, 1) 187 188 def test_offboarding_marked_failed_after_max_attempts(self): 189 """A persistently failing offboarding goes terminal without touching the user.""" 190 offboarding = UserOffboarding.objects.create( 191 user=self.user, 192 scheduled_at=now() - timedelta(minutes=1), 193 action=OffboardingAction.DEACTIVATE, 194 ) 195 with patch( 196 "authentik.enterprise.lifecycle.offboarding.actions.Event.new", 197 side_effect=RuntimeError("boom"), 198 ): 199 for _ in range(MAX_OFFBOARDING_ATTEMPTS): 200 with self.assertRaises(RuntimeError): 201 execute_offboarding(str(offboarding.pk)) 202 203 offboarding.refresh_from_db() 204 self.user.refresh_from_db() 205 self.assertEqual(offboarding.status, OffboardingStatus.FAILED) 206 self.assertEqual(offboarding.attempts, MAX_OFFBOARDING_ATTEMPTS) 207 self.assertTrue(self.user.is_active) 208 209 def test_redispatch_of_completed_offboarding_is_noop(self): 210 """Re-dispatching an already-executed offboarding does not run it again.""" 211 offboarding = UserOffboarding.objects.create( 212 user=self.user, 213 scheduled_at=now() - timedelta(minutes=1), 214 action=OffboardingAction.DEACTIVATE, 215 ) 216 execute_offboarding(str(offboarding.pk)) 217 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1) 218 # The sweeper may re-queue the same row; the status guard must no-op. 219 execute_offboarding(str(offboarding.pk)) 220 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1) 221 222 def test_future_offboarding_not_picked_up(self): 223 offboarding = UserOffboarding.objects.create( 224 user=self.user, 225 scheduled_at=now() + timedelta(days=1), 226 action=OffboardingAction.DEACTIVATE, 227 ) 228 execute_due_offboardings.send() 229 offboarding.refresh_from_db() 230 self.user.refresh_from_db() 231 self.assertEqual(offboarding.status, OffboardingStatus.PENDING) 232 self.assertTrue(self.user.is_active)
Similar to TransactionTestCase, but use transaction.atomic() to achieve
test isolation.
In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior).
On database backends with no transaction support, TestCase behaves as TransactionTestCase.
110 @classmethod 111 def setUpTestData(cls): 112 config = apps.get_app_config("authentik_tasks_schedules") 113 config._on_startup_callback(None)
Load initial data for the TestCase.
118 def test_due_offboarding_dispatched_under_schedule(self): 119 """The sweeper dispatches each due offboarding.""" 120 UserOffboarding.objects.create( 121 user=self.user, 122 scheduled_at=now() - timedelta(minutes=1), 123 action=OffboardingAction.DEACTIVATE, 124 ) 125 with patch( 126 "authentik.enterprise.lifecycle.offboarding.tasks.execute_offboarding.send_with_options" 127 ) as send: 128 # Dispatch through the worker so CurrentTask (and its rel_obj) is populated. 129 execute_due_offboardings.send() 130 send.assert_called_once()
The sweeper dispatches each due offboarding.
132 def test_due_offboarding_executed(self): 133 offboarding = UserOffboarding.objects.create( 134 user=self.user, 135 scheduled_at=now() - timedelta(minutes=1), 136 action=OffboardingAction.DEACTIVATE, 137 ) 138 execute_offboarding(str(offboarding.pk)) 139 offboarding.refresh_from_db() 140 self.user.refresh_from_db() 141 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 142 self.assertIsNotNone(offboarding.executed_at) 143 self.assertFalse(self.user.is_active)
145 def test_audit_event_attributed_to_initiator(self): 146 """The audit event names the admin who scheduled it, not the offboarded user.""" 147 admin = create_test_admin_user() 148 offboarding = UserOffboarding.objects.create( 149 user=self.user, 150 scheduled_at=now() - timedelta(minutes=1), 151 action=OffboardingAction.DEACTIVATE, 152 created_by=admin, 153 ) 154 execute_offboarding(str(offboarding.pk)) 155 event = Event.objects.filter(action=EventAction.USER_OFFBOARDED).latest("created") 156 self.assertEqual(event.user.get("pk"), admin.pk) 157 self.assertNotEqual(event.user.get("pk"), self.user.pk) 158 self.assertEqual(event.context.get("user_pk"), self.user.pk)
The audit event names the admin who scheduled it, not the offboarded user.
160 def test_failed_execution_is_atomic_and_retryable(self): 161 """A mid-way failure rolls back every change and leaves the row retryable.""" 162 _add_session(self.user) 163 _add_token(self.user) 164 offboarding = UserOffboarding.objects.create( 165 user=self.user, 166 scheduled_at=now() - timedelta(minutes=1), 167 action=OffboardingAction.DEACTIVATE, 168 ) 169 # Sessions/tokens are revoked before the audit event is built; make the 170 # event raise so the failure lands mid-offboarding. 171 with patch( 172 "authentik.enterprise.lifecycle.offboarding.actions.Event.new", 173 side_effect=RuntimeError("boom"), 174 ): 175 with self.assertRaises(RuntimeError): 176 execute_offboarding(str(offboarding.pk)) 177 178 offboarding.refresh_from_db() 179 self.user.refresh_from_db() 180 # Nothing was applied: user still active, sessions/tokens intact. 181 self.assertTrue(self.user.is_active) 182 self.assertTrue(AuthenticatedSession.objects.filter(user=self.user).exists()) 183 self.assertTrue(Token.objects.filter(user=self.user).exists()) 184 # Still retryable, with the failed attempt recorded. 185 self.assertEqual(offboarding.status, OffboardingStatus.PENDING) 186 self.assertEqual(offboarding.attempts, 1)
A mid-way failure rolls back every change and leaves the row retryable.
188 def test_offboarding_marked_failed_after_max_attempts(self): 189 """A persistently failing offboarding goes terminal without touching the user.""" 190 offboarding = UserOffboarding.objects.create( 191 user=self.user, 192 scheduled_at=now() - timedelta(minutes=1), 193 action=OffboardingAction.DEACTIVATE, 194 ) 195 with patch( 196 "authentik.enterprise.lifecycle.offboarding.actions.Event.new", 197 side_effect=RuntimeError("boom"), 198 ): 199 for _ in range(MAX_OFFBOARDING_ATTEMPTS): 200 with self.assertRaises(RuntimeError): 201 execute_offboarding(str(offboarding.pk)) 202 203 offboarding.refresh_from_db() 204 self.user.refresh_from_db() 205 self.assertEqual(offboarding.status, OffboardingStatus.FAILED) 206 self.assertEqual(offboarding.attempts, MAX_OFFBOARDING_ATTEMPTS) 207 self.assertTrue(self.user.is_active)
A persistently failing offboarding goes terminal without touching the user.
209 def test_redispatch_of_completed_offboarding_is_noop(self): 210 """Re-dispatching an already-executed offboarding does not run it again.""" 211 offboarding = UserOffboarding.objects.create( 212 user=self.user, 213 scheduled_at=now() - timedelta(minutes=1), 214 action=OffboardingAction.DEACTIVATE, 215 ) 216 execute_offboarding(str(offboarding.pk)) 217 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1) 218 # The sweeper may re-queue the same row; the status guard must no-op. 219 execute_offboarding(str(offboarding.pk)) 220 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1)
Re-dispatching an already-executed offboarding does not run it again.
222 def test_future_offboarding_not_picked_up(self): 223 offboarding = UserOffboarding.objects.create( 224 user=self.user, 225 scheduled_at=now() + timedelta(days=1), 226 action=OffboardingAction.DEACTIVATE, 227 ) 228 execute_due_offboardings.send() 229 offboarding.refresh_from_db() 230 self.user.refresh_from_db() 231 self.assertEqual(offboarding.status, OffboardingStatus.PENDING) 232 self.assertTrue(self.user.is_active)
235class TestOffboardingConcurrency(TransactionTestCase): 236 """Two workers must not offboard the same user twice.""" 237 238 def setUp(self): 239 self.user = create_test_user() 240 241 def test_concurrent_dispatch_executes_once(self): 242 offboarding = UserOffboarding.objects.create( 243 user=self.user, 244 scheduled_at=now() - timedelta(minutes=1), 245 action=OffboardingAction.DEACTIVATE, 246 ) 247 pk = str(offboarding.pk) 248 249 inside_lock = ThreadEvent() # set once a worker holds the row lock 250 may_finish = ThreadEvent() # released once the other worker is running 251 errors: list = [] 252 real_offboard = offboard_user 253 254 def slow_offboard(*args, **kwargs): 255 # The worker that reaches this holds the row lock; hold it briefly so 256 # the other worker is forced to contend for the same PENDING row. 257 inside_lock.set() 258 may_finish.wait(timeout=10) 259 return real_offboard(*args, **kwargs) 260 261 class Worker(Thread): 262 __test__ = False 263 264 def run(self): 265 try: 266 execute_offboarding(pk) 267 except Exception as exc: # noqa: BLE001 268 errors.append(exc) 269 finally: 270 connection.close() 271 272 with patch( 273 "authentik.enterprise.lifecycle.offboarding.actions.offboard_user", 274 side_effect=slow_offboard, 275 ): 276 first = Worker() 277 first.start() 278 self.assertTrue(inside_lock.wait(timeout=10), "worker never acquired the lock") 279 # First worker now holds the lock inside slow_offboard. The second must 280 # block on select_for_update; give it a moment to reach the lock, then 281 # let the first finish. (The single-execution invariant holds for every 282 # interleaving, since the first worker locks the row before the second starts.) 283 second = Worker() 284 second.start() 285 time.sleep(0.5) 286 may_finish.set() 287 first.join(timeout=15) 288 second.join(timeout=15) 289 290 self.assertEqual(errors, []) 291 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1) 292 offboarding.refresh_from_db() 293 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 294 self.user.refresh_from_db() 295 self.assertFalse(self.user.is_active) 296 297 def test_cancel_racing_execution_does_not_clobber(self): 298 """A cancel that loses the race to a running execution must not overwrite it.""" 299 offboarding = UserOffboarding.objects.create( 300 user=self.user, 301 scheduled_at=now() - timedelta(minutes=1), 302 action=OffboardingAction.DEACTIVATE, 303 ) 304 pk = str(offboarding.pk) 305 306 inside_lock = ThreadEvent() # set once the worker holds the row lock 307 may_finish = ThreadEvent() # released once the canceller is contending 308 errors: list = [] 309 cancelled: list = [] 310 real_offboard = offboard_user 311 312 def slow_offboard(*args, **kwargs): 313 inside_lock.set() 314 may_finish.wait(timeout=10) 315 return real_offboard(*args, **kwargs) 316 317 class Worker(Thread): 318 __test__ = False 319 320 def run(self): 321 try: 322 execute_offboarding(pk) 323 except Exception as exc: # noqa: BLE001 324 errors.append(exc) 325 finally: 326 connection.close() 327 328 class Canceller(Thread): 329 __test__ = False 330 331 def run(self): 332 try: 333 cancelled.append(UserOffboarding.objects.get(pk=pk).cancel()) 334 except Exception as exc: # noqa: BLE001 335 errors.append(exc) 336 finally: 337 connection.close() 338 339 with patch( 340 "authentik.enterprise.lifecycle.offboarding.actions.offboard_user", 341 side_effect=slow_offboard, 342 ): 343 worker = Worker() 344 worker.start() 345 self.assertTrue(inside_lock.wait(timeout=10), "worker never acquired the lock") 346 # Worker holds the lock mid-execution; the cancel must block on it, 347 # then observe COMPLETED and refuse instead of clobbering the status. 348 canceller = Canceller() 349 canceller.start() 350 time.sleep(0.5) 351 may_finish.set() 352 worker.join(timeout=15) 353 canceller.join(timeout=15) 354 355 self.assertEqual(errors, []) 356 self.assertEqual(cancelled, [False]) 357 offboarding.refresh_from_db() 358 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 359 self.user.refresh_from_db() 360 self.assertFalse(self.user.is_active)
Two workers must not offboard the same user twice.
241 def test_concurrent_dispatch_executes_once(self): 242 offboarding = UserOffboarding.objects.create( 243 user=self.user, 244 scheduled_at=now() - timedelta(minutes=1), 245 action=OffboardingAction.DEACTIVATE, 246 ) 247 pk = str(offboarding.pk) 248 249 inside_lock = ThreadEvent() # set once a worker holds the row lock 250 may_finish = ThreadEvent() # released once the other worker is running 251 errors: list = [] 252 real_offboard = offboard_user 253 254 def slow_offboard(*args, **kwargs): 255 # The worker that reaches this holds the row lock; hold it briefly so 256 # the other worker is forced to contend for the same PENDING row. 257 inside_lock.set() 258 may_finish.wait(timeout=10) 259 return real_offboard(*args, **kwargs) 260 261 class Worker(Thread): 262 __test__ = False 263 264 def run(self): 265 try: 266 execute_offboarding(pk) 267 except Exception as exc: # noqa: BLE001 268 errors.append(exc) 269 finally: 270 connection.close() 271 272 with patch( 273 "authentik.enterprise.lifecycle.offboarding.actions.offboard_user", 274 side_effect=slow_offboard, 275 ): 276 first = Worker() 277 first.start() 278 self.assertTrue(inside_lock.wait(timeout=10), "worker never acquired the lock") 279 # First worker now holds the lock inside slow_offboard. The second must 280 # block on select_for_update; give it a moment to reach the lock, then 281 # let the first finish. (The single-execution invariant holds for every 282 # interleaving, since the first worker locks the row before the second starts.) 283 second = Worker() 284 second.start() 285 time.sleep(0.5) 286 may_finish.set() 287 first.join(timeout=15) 288 second.join(timeout=15) 289 290 self.assertEqual(errors, []) 291 self.assertEqual(Event.objects.filter(action=EventAction.USER_OFFBOARDED).count(), 1) 292 offboarding.refresh_from_db() 293 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 294 self.user.refresh_from_db() 295 self.assertFalse(self.user.is_active)
297 def test_cancel_racing_execution_does_not_clobber(self): 298 """A cancel that loses the race to a running execution must not overwrite it.""" 299 offboarding = UserOffboarding.objects.create( 300 user=self.user, 301 scheduled_at=now() - timedelta(minutes=1), 302 action=OffboardingAction.DEACTIVATE, 303 ) 304 pk = str(offboarding.pk) 305 306 inside_lock = ThreadEvent() # set once the worker holds the row lock 307 may_finish = ThreadEvent() # released once the canceller is contending 308 errors: list = [] 309 cancelled: list = [] 310 real_offboard = offboard_user 311 312 def slow_offboard(*args, **kwargs): 313 inside_lock.set() 314 may_finish.wait(timeout=10) 315 return real_offboard(*args, **kwargs) 316 317 class Worker(Thread): 318 __test__ = False 319 320 def run(self): 321 try: 322 execute_offboarding(pk) 323 except Exception as exc: # noqa: BLE001 324 errors.append(exc) 325 finally: 326 connection.close() 327 328 class Canceller(Thread): 329 __test__ = False 330 331 def run(self): 332 try: 333 cancelled.append(UserOffboarding.objects.get(pk=pk).cancel()) 334 except Exception as exc: # noqa: BLE001 335 errors.append(exc) 336 finally: 337 connection.close() 338 339 with patch( 340 "authentik.enterprise.lifecycle.offboarding.actions.offboard_user", 341 side_effect=slow_offboard, 342 ): 343 worker = Worker() 344 worker.start() 345 self.assertTrue(inside_lock.wait(timeout=10), "worker never acquired the lock") 346 # Worker holds the lock mid-execution; the cancel must block on it, 347 # then observe COMPLETED and refuse instead of clobbering the status. 348 canceller = Canceller() 349 canceller.start() 350 time.sleep(0.5) 351 may_finish.set() 352 worker.join(timeout=15) 353 canceller.join(timeout=15) 354 355 self.assertEqual(errors, []) 356 self.assertEqual(cancelled, [False]) 357 offboarding.refresh_from_db() 358 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 359 self.user.refresh_from_db() 360 self.assertFalse(self.user.is_active)
A cancel that loses the race to a running execution must not overwrite it.
363@enterprise_test() 364class TestOffboardingAPI(APITestCase): 365 def setUp(self): 366 self.admin = create_test_admin_user() 367 self.client.force_login(self.admin) 368 self.user = create_test_user() 369 370 @classmethod 371 def setUpTestData(cls): 372 config = apps.get_app_config("authentik_tasks_schedules") 373 config._on_startup_callback(None) 374 375 def test_create(self): 376 response = self.client.post( 377 reverse("authentik_api:useroffboarding-list"), 378 { 379 "user": self.user.pk, 380 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 381 "action": OffboardingAction.DELETE, 382 }, 383 ) 384 self.assertEqual(response.status_code, 201) 385 self.assertEqual(response.data["status"], OffboardingStatus.PENDING) 386 offboarding = UserOffboarding.objects.get(pk=response.data["id"]) 387 self.assertEqual(offboarding.created_by, self.admin) 388 389 def test_create_in_past_rejected(self): 390 response = self.client.post( 391 reverse("authentik_api:useroffboarding-list"), 392 { 393 "user": self.user.pk, 394 "scheduled_at": (now() - timedelta(days=1)).isoformat(), 395 "action": OffboardingAction.DEACTIVATE, 396 }, 397 ) 398 self.assertEqual(response.status_code, 400) 399 self.assertIn("scheduled_at", response.data) 400 401 def test_duplicate_pending_rejected(self): 402 UserOffboarding.objects.create( 403 user=self.user, 404 scheduled_at=now() + timedelta(days=1), 405 action=OffboardingAction.DEACTIVATE, 406 ) 407 response = self.client.post( 408 reverse("authentik_api:useroffboarding-list"), 409 { 410 "user": self.user.pk, 411 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 412 "action": OffboardingAction.DEACTIVATE, 413 }, 414 ) 415 self.assertEqual(response.status_code, 400) 416 self.assertJSONEqual( 417 response.content, 418 {"non_field_errors": ["The fields user must make a unique set."]}, 419 ) 420 421 def test_duplicate_pending_race_returns_400(self): 422 """If two requests race past validation, the DB constraint yields a 400, not a 500.""" 423 UserOffboarding.objects.create( 424 user=self.user, 425 scheduled_at=now() + timedelta(days=1), 426 action=OffboardingAction.DEACTIVATE, 427 ) 428 # Simulate the Time-of-Check to Time-of-Use: bypass the duplicate pre-check so the 429 # insert is the first place the conflict is detected (the partial unique constraint). 430 with patch.object(UserOffboardingSerializer, "validate", new=lambda self, attrs: attrs): 431 response = self.client.post( 432 reverse("authentik_api:useroffboarding-list"), 433 { 434 "user": self.user.pk, 435 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 436 "action": OffboardingAction.DEACTIVATE, 437 }, 438 ) 439 self.assertEqual(response.status_code, 400) 440 self.assertJSONEqual( 441 response.content, 442 {"non_field_errors": ["The fields user must make a unique set."]}, 443 ) # The losing insert did not create a second pending row. 444 self.assertEqual( 445 UserOffboarding.objects.filter( 446 user=self.user, status=OffboardingStatus.PENDING 447 ).count(), 448 1, 449 ) 450 451 def test_offboard_self_rejected(self): 452 response = self.client.post( 453 reverse("authentik_api:useroffboarding-list"), 454 { 455 "user": self.admin.pk, 456 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 457 "action": OffboardingAction.DEACTIVATE, 458 }, 459 ) 460 self.assertEqual(response.status_code, 400) 461 self.assertIn("user", response.data) 462 463 def test_offboard_internal_service_account_rejected(self): 464 service_account = User.objects.create( 465 username=generate_id(), type=UserTypes.INTERNAL_SERVICE_ACCOUNT 466 ) 467 response = self.client.post( 468 reverse("authentik_api:useroffboarding-list"), 469 { 470 "user": service_account.pk, 471 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 472 "action": OffboardingAction.DEACTIVATE, 473 }, 474 ) 475 self.assertEqual(response.status_code, 400) 476 self.assertIn("user", response.data) 477 478 def test_cancel(self): 479 offboarding = UserOffboarding.objects.create( 480 user=self.user, 481 scheduled_at=now() + timedelta(days=1), 482 action=OffboardingAction.DEACTIVATE, 483 ) 484 response = self.client.delete( 485 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 486 ) 487 self.assertEqual(response.status_code, 204) 488 # The row is retained as an audit record, transitioned to CANCELED. 489 offboarding.refresh_from_db() 490 self.assertEqual(offboarding.status, OffboardingStatus.CANCELED) 491 self.assertIsNotNone(offboarding.executed_at) 492 493 def test_cancel_frees_user_for_rescheduling(self): 494 """A cancelled offboarding no longer blocks the unique-pending constraint.""" 495 offboarding = UserOffboarding.objects.create( 496 user=self.user, 497 scheduled_at=now() + timedelta(days=1), 498 action=OffboardingAction.DEACTIVATE, 499 ) 500 offboarding.cancel() 501 response = self.client.post( 502 reverse("authentik_api:useroffboarding-list"), 503 { 504 "user": self.user.pk, 505 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 506 "action": OffboardingAction.DEACTIVATE, 507 }, 508 ) 509 self.assertEqual(response.status_code, 201) 510 511 def test_cancel_non_pending_rejected(self): 512 offboarding = UserOffboarding.objects.create( 513 user=self.user, 514 scheduled_at=now() + timedelta(days=1), 515 action=OffboardingAction.DEACTIVATE, 516 status=OffboardingStatus.COMPLETED, 517 ) 518 response = self.client.delete( 519 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 520 ) 521 self.assertEqual(response.status_code, 400) 522 offboarding.refresh_from_db() 523 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED) 524 525 def test_cancel_own_offboarding_rejected(self): 526 """Separation of duties: you cannot cancel an offboarding that targets you.""" 527 offboarding = UserOffboarding.objects.create( 528 user=self.admin, 529 scheduled_at=now() + timedelta(days=1), 530 action=OffboardingAction.DEACTIVATE, 531 ) 532 response = self.client.delete( 533 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 534 ) 535 self.assertEqual(response.status_code, 403) 536 offboarding.refresh_from_db() 537 self.assertEqual(offboarding.status, OffboardingStatus.PENDING) 538 539 def test_update_not_allowed(self): 540 """Records are immutable: PUT/PATCH must not rewrite an offboarding.""" 541 offboarding = UserOffboarding.objects.create( 542 user=self.user, 543 scheduled_at=now() + timedelta(days=1), 544 action=OffboardingAction.DEACTIVATE, 545 ) 546 url = reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 547 for method in (self.client.put, self.client.patch): 548 response = method(url, {"action": OffboardingAction.DELETE}) 549 self.assertEqual(response.status_code, 405) 550 offboarding.refresh_from_db() 551 self.assertEqual(offboarding.action, OffboardingAction.DEACTIVATE) 552 553 def test_generated_filter_keeps_rows_of_deleted_rules(self): 554 from authentik.enterprise.lifecycle.expiration.models import UserExpirationRule 555 556 with patch( 557 "authentik.enterprise.lifecycle.expiration.tasks.apply_expiration_rule.send_with_options" 558 ): 559 rule = UserExpirationRule.objects.create(name=generate_id()) 560 generated = UserOffboarding.objects.create( 561 user=create_test_user(), 562 rule=rule, 563 generated=True, 564 scheduled_at=now(), 565 status=OffboardingStatus.COMPLETED, 566 ) 567 manual = UserOffboarding.objects.create(user=self.user, scheduled_at=now()) 568 rule.delete() 569 url = reverse("authentik_api:useroffboarding-list") 570 for value, expected in (("true", generated), ("false", manual)): 571 with self.subTest(generated=value): 572 response = self.client.get(url, {"generated": value}) 573 self.assertEqual(response.status_code, 200) 574 results = response.json()["results"] 575 self.assertEqual([row["id"] for row in results], [str(expected.pk)]) 576 self.assertEqual(results[0]["generated"], value == "true") 577 self.assertIsNone(results[0]["rule"])
Similar to TransactionTestCase, but use transaction.atomic() to achieve
test isolation.
In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior).
On database backends with no transaction support, TestCase behaves as TransactionTestCase.
365 def setUp(self): 366 self.admin = create_test_admin_user() 367 self.client.force_login(self.admin) 368 self.user = create_test_user()
Hook method for setting up the test fixture before exercising it.
370 @classmethod 371 def setUpTestData(cls): 372 config = apps.get_app_config("authentik_tasks_schedules") 373 config._on_startup_callback(None)
Load initial data for the TestCase.
375 def test_create(self): 376 response = self.client.post( 377 reverse("authentik_api:useroffboarding-list"), 378 { 379 "user": self.user.pk, 380 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 381 "action": OffboardingAction.DELETE, 382 }, 383 ) 384 self.assertEqual(response.status_code, 201) 385 self.assertEqual(response.data["status"], OffboardingStatus.PENDING) 386 offboarding = UserOffboarding.objects.get(pk=response.data["id"]) 387 self.assertEqual(offboarding.created_by, self.admin)
389 def test_create_in_past_rejected(self): 390 response = self.client.post( 391 reverse("authentik_api:useroffboarding-list"), 392 { 393 "user": self.user.pk, 394 "scheduled_at": (now() - timedelta(days=1)).isoformat(), 395 "action": OffboardingAction.DEACTIVATE, 396 }, 397 ) 398 self.assertEqual(response.status_code, 400) 399 self.assertIn("scheduled_at", response.data)
401 def test_duplicate_pending_rejected(self): 402 UserOffboarding.objects.create( 403 user=self.user, 404 scheduled_at=now() + timedelta(days=1), 405 action=OffboardingAction.DEACTIVATE, 406 ) 407 response = self.client.post( 408 reverse("authentik_api:useroffboarding-list"), 409 { 410 "user": self.user.pk, 411 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 412 "action": OffboardingAction.DEACTIVATE, 413 }, 414 ) 415 self.assertEqual(response.status_code, 400) 416 self.assertJSONEqual( 417 response.content, 418 {"non_field_errors": ["The fields user must make a unique set."]}, 419 )
421 def test_duplicate_pending_race_returns_400(self): 422 """If two requests race past validation, the DB constraint yields a 400, not a 500.""" 423 UserOffboarding.objects.create( 424 user=self.user, 425 scheduled_at=now() + timedelta(days=1), 426 action=OffboardingAction.DEACTIVATE, 427 ) 428 # Simulate the Time-of-Check to Time-of-Use: bypass the duplicate pre-check so the 429 # insert is the first place the conflict is detected (the partial unique constraint). 430 with patch.object(UserOffboardingSerializer, "validate", new=lambda self, attrs: attrs): 431 response = self.client.post( 432 reverse("authentik_api:useroffboarding-list"), 433 { 434 "user": self.user.pk, 435 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 436 "action": OffboardingAction.DEACTIVATE, 437 }, 438 ) 439 self.assertEqual(response.status_code, 400) 440 self.assertJSONEqual( 441 response.content, 442 {"non_field_errors": ["The fields user must make a unique set."]}, 443 ) # The losing insert did not create a second pending row. 444 self.assertEqual( 445 UserOffboarding.objects.filter( 446 user=self.user, status=OffboardingStatus.PENDING 447 ).count(), 448 1, 449 )
If two requests race past validation, the DB constraint yields a 400, not a 500.
451 def test_offboard_self_rejected(self): 452 response = self.client.post( 453 reverse("authentik_api:useroffboarding-list"), 454 { 455 "user": self.admin.pk, 456 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 457 "action": OffboardingAction.DEACTIVATE, 458 }, 459 ) 460 self.assertEqual(response.status_code, 400) 461 self.assertIn("user", response.data)
463 def test_offboard_internal_service_account_rejected(self): 464 service_account = User.objects.create( 465 username=generate_id(), type=UserTypes.INTERNAL_SERVICE_ACCOUNT 466 ) 467 response = self.client.post( 468 reverse("authentik_api:useroffboarding-list"), 469 { 470 "user": service_account.pk, 471 "scheduled_at": (now() + timedelta(days=1)).isoformat(), 472 "action": OffboardingAction.DEACTIVATE, 473 }, 474 ) 475 self.assertEqual(response.status_code, 400) 476 self.assertIn("user", response.data)
478 def test_cancel(self): 479 offboarding = UserOffboarding.objects.create( 480 user=self.user, 481 scheduled_at=now() + timedelta(days=1), 482 action=OffboardingAction.DEACTIVATE, 483 ) 484 response = self.client.delete( 485 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 486 ) 487 self.assertEqual(response.status_code, 204) 488 # The row is retained as an audit record, transitioned to CANCELED. 489 offboarding.refresh_from_db() 490 self.assertEqual(offboarding.status, OffboardingStatus.CANCELED) 491 self.assertIsNotNone(offboarding.executed_at)
493 def test_cancel_frees_user_for_rescheduling(self): 494 """A cancelled offboarding no longer blocks the unique-pending constraint.""" 495 offboarding = UserOffboarding.objects.create( 496 user=self.user, 497 scheduled_at=now() + timedelta(days=1), 498 action=OffboardingAction.DEACTIVATE, 499 ) 500 offboarding.cancel() 501 response = self.client.post( 502 reverse("authentik_api:useroffboarding-list"), 503 { 504 "user": self.user.pk, 505 "scheduled_at": (now() + timedelta(days=2)).isoformat(), 506 "action": OffboardingAction.DEACTIVATE, 507 }, 508 ) 509 self.assertEqual(response.status_code, 201)
A cancelled offboarding no longer blocks the unique-pending constraint.
511 def test_cancel_non_pending_rejected(self): 512 offboarding = UserOffboarding.objects.create( 513 user=self.user, 514 scheduled_at=now() + timedelta(days=1), 515 action=OffboardingAction.DEACTIVATE, 516 status=OffboardingStatus.COMPLETED, 517 ) 518 response = self.client.delete( 519 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 520 ) 521 self.assertEqual(response.status_code, 400) 522 offboarding.refresh_from_db() 523 self.assertEqual(offboarding.status, OffboardingStatus.COMPLETED)
525 def test_cancel_own_offboarding_rejected(self): 526 """Separation of duties: you cannot cancel an offboarding that targets you.""" 527 offboarding = UserOffboarding.objects.create( 528 user=self.admin, 529 scheduled_at=now() + timedelta(days=1), 530 action=OffboardingAction.DEACTIVATE, 531 ) 532 response = self.client.delete( 533 reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 534 ) 535 self.assertEqual(response.status_code, 403) 536 offboarding.refresh_from_db() 537 self.assertEqual(offboarding.status, OffboardingStatus.PENDING)
Separation of duties: you cannot cancel an offboarding that targets you.
539 def test_update_not_allowed(self): 540 """Records are immutable: PUT/PATCH must not rewrite an offboarding.""" 541 offboarding = UserOffboarding.objects.create( 542 user=self.user, 543 scheduled_at=now() + timedelta(days=1), 544 action=OffboardingAction.DEACTIVATE, 545 ) 546 url = reverse("authentik_api:useroffboarding-detail", kwargs={"pk": offboarding.pk}) 547 for method in (self.client.put, self.client.patch): 548 response = method(url, {"action": OffboardingAction.DELETE}) 549 self.assertEqual(response.status_code, 405) 550 offboarding.refresh_from_db() 551 self.assertEqual(offboarding.action, OffboardingAction.DEACTIVATE)
Records are immutable: PUT/PATCH must not rewrite an offboarding.
553 def test_generated_filter_keeps_rows_of_deleted_rules(self): 554 from authentik.enterprise.lifecycle.expiration.models import UserExpirationRule 555 556 with patch( 557 "authentik.enterprise.lifecycle.expiration.tasks.apply_expiration_rule.send_with_options" 558 ): 559 rule = UserExpirationRule.objects.create(name=generate_id()) 560 generated = UserOffboarding.objects.create( 561 user=create_test_user(), 562 rule=rule, 563 generated=True, 564 scheduled_at=now(), 565 status=OffboardingStatus.COMPLETED, 566 ) 567 manual = UserOffboarding.objects.create(user=self.user, scheduled_at=now()) 568 rule.delete() 569 url = reverse("authentik_api:useroffboarding-list") 570 for value, expected in (("true", generated), ("false", manual)): 571 with self.subTest(generated=value): 572 response = self.client.get(url, {"generated": value}) 573 self.assertEqual(response.status_code, 200) 574 results = response.json()["results"] 575 self.assertEqual([row["id"] for row in results], [str(expected.pk)]) 576 self.assertEqual(results[0]["generated"], value == "true") 577 self.assertIsNone(results[0]["rule"])