authentik.core.tests.test_activity

Activity recording, attribution, and historical backfill.

  1"""Activity recording, attribution, and historical backfill."""
  2
  3from concurrent.futures import ThreadPoolExecutor
  4from datetime import timedelta
  5from importlib import import_module
  6from threading import Barrier
  7from unittest.mock import patch
  8
  9from django.db import close_old_connections, connection
 10from django.test import TestCase, TransactionTestCase
 11from django.utils.timezone import now
 12from freezegun import freeze_time
 13
 14from authentik.core.models import USER_ACTIVITY_INTERVAL, UserActivity
 15from authentik.core.tests.utils import create_test_user
 16from authentik.events.models import Event, EventAction
 17from authentik.events.signals import event_post_save_activity
 18
 19
 20class TestUserActivity(TestCase):
 21    def test_monotonic_throttle_boundaries_and_invalid_ids(self):
 22        user = create_test_user()
 23        at = now()
 24        UserActivity.objects.record(user.pk, at)
 25        for delta in (-timedelta(days=1), USER_ACTIVITY_INTERVAL - timedelta(microseconds=1)):
 26            UserActivity.objects.record(user.pk, at + delta)
 27            self.assertEqual(UserActivity.objects.get(user=user).last_activity_at, at)
 28        UserActivity.objects.record(user.pk, at + USER_ACTIVITY_INTERVAL)
 29        self.assertEqual(
 30            UserActivity.objects.get(user=user).last_activity_at, at + USER_ACTIVITY_INTERVAL
 31        )
 32        user.delete()
 33        for invalid in (None, "1", True, 10**100):
 34            UserActivity.objects.record(invalid, at)
 35        self.assertFalse(UserActivity.objects.exists())
 36
 37    def test_late_activity_for_deleted_user_is_allowed(self):
 38        user = create_test_user()
 39        user_id = user.pk
 40        UserActivity.objects.record(user_id)
 41        user.delete()
 42        self.assertFalse(UserActivity.objects.filter(user_id=user_id).exists())
 43        UserActivity.objects.record(user_id)
 44        self.assertTrue(UserActivity.objects.filter(user_id=user_id).exists())
 45
 46    def test_record_writes_to_primary_with_read_replicas(self):
 47        user = create_test_user()
 48        with patch("authentik.root.db.router.FailoverRouter.db_for_read", return_value="replica"):
 49            UserActivity.objects.record(user.pk)
 50        self.assertTrue(UserActivity.objects.filter(user=user).exists())
 51
 52    def test_event_attribution_and_resaves(self):
 53        admin, target = create_test_user(), create_test_user()
 54        at = now()
 55        with freeze_time(at):
 56            event = Event.new(EventAction.LOGIN)
 57            event.user = {"pk": admin.pk, "on_behalf_of": {"pk": target.pk}}
 58            event.save()
 59        self.assertFalse(UserActivity.objects.filter(user=target).exists())
 60        with freeze_time(at + timedelta(days=1)):
 61            event.save()
 62            event_post_save_activity(Event, event, created=True, raw=True)
 63        self.assertEqual(UserActivity.objects.get(user=admin).last_activity_at, at)
 64
 65    def test_backfill_matches_attribution_and_preserves_newer_activity(self):
 66        users = [create_test_user() for _ in range(3)]
 67        at = now() - timedelta(days=2)
 68        with patch("authentik.events.signals.UserActivity.objects.record"):
 69            for index, action in enumerate(
 70                (EventAction.LOGIN, EventAction.AUTHORIZE_APPLICATION, EventAction.LOGIN_FAILED)
 71            ):
 72                with freeze_time(at):
 73                    Event.new(action).set_user(users[index]).save()
 74            event = Event.new(EventAction.LOGIN)
 75            event.user = {"pk": "invalid", "on_behalf_of": {"pk": users[2].pk}}
 76            event.save()
 77        UserActivity.objects.record(users[0].pk)
 78        current = UserActivity.objects.get(user=users[0]).last_activity_at
 79        migration = import_module("authentik.core.migrations.0069_useractivity")
 80        with connection.cursor() as cursor:
 81            cursor.execute(migration.Migration.operations[-1].sql)
 82        self.assertEqual(UserActivity.objects.get(user=users[0]).last_activity_at, current)
 83        self.assertEqual(UserActivity.objects.get(user=users[1]).last_activity_at, at)
 84        self.assertFalse(UserActivity.objects.filter(user=users[2]).exists())
 85
 86
 87class TestConcurrentActivityRecording(TransactionTestCase):
 88    def test_concurrent_first_writes_keep_the_newest_timestamp(self):
 89        user = create_test_user()
 90        at = now()
 91        barrier = Barrier(2)
 92
 93        def record(timestamp):
 94            close_old_connections()
 95            try:
 96                with connection.cursor() as cursor:
 97                    cursor.execute("SET statement_timeout = '10s'")
 98                barrier.wait(timeout=5)
 99                UserActivity.objects.record(user.pk, timestamp)
100            finally:
101                connection.close()
102
103        with ThreadPoolExecutor(max_workers=2) as pool:
104            futures = [
105                pool.submit(record, timestamp) for timestamp in (at, at + USER_ACTIVITY_INTERVAL)
106            ]
107            try:
108                for future in futures:
109                    future.result(timeout=15)
110            finally:
111                barrier.abort()
112        self.assertEqual(
113            UserActivity.objects.get(user=user).last_activity_at, at + USER_ACTIVITY_INTERVAL
114        )
class TestUserActivity(django.test.testcases.TestCase):
21class TestUserActivity(TestCase):
22    def test_monotonic_throttle_boundaries_and_invalid_ids(self):
23        user = create_test_user()
24        at = now()
25        UserActivity.objects.record(user.pk, at)
26        for delta in (-timedelta(days=1), USER_ACTIVITY_INTERVAL - timedelta(microseconds=1)):
27            UserActivity.objects.record(user.pk, at + delta)
28            self.assertEqual(UserActivity.objects.get(user=user).last_activity_at, at)
29        UserActivity.objects.record(user.pk, at + USER_ACTIVITY_INTERVAL)
30        self.assertEqual(
31            UserActivity.objects.get(user=user).last_activity_at, at + USER_ACTIVITY_INTERVAL
32        )
33        user.delete()
34        for invalid in (None, "1", True, 10**100):
35            UserActivity.objects.record(invalid, at)
36        self.assertFalse(UserActivity.objects.exists())
37
38    def test_late_activity_for_deleted_user_is_allowed(self):
39        user = create_test_user()
40        user_id = user.pk
41        UserActivity.objects.record(user_id)
42        user.delete()
43        self.assertFalse(UserActivity.objects.filter(user_id=user_id).exists())
44        UserActivity.objects.record(user_id)
45        self.assertTrue(UserActivity.objects.filter(user_id=user_id).exists())
46
47    def test_record_writes_to_primary_with_read_replicas(self):
48        user = create_test_user()
49        with patch("authentik.root.db.router.FailoverRouter.db_for_read", return_value="replica"):
50            UserActivity.objects.record(user.pk)
51        self.assertTrue(UserActivity.objects.filter(user=user).exists())
52
53    def test_event_attribution_and_resaves(self):
54        admin, target = create_test_user(), create_test_user()
55        at = now()
56        with freeze_time(at):
57            event = Event.new(EventAction.LOGIN)
58            event.user = {"pk": admin.pk, "on_behalf_of": {"pk": target.pk}}
59            event.save()
60        self.assertFalse(UserActivity.objects.filter(user=target).exists())
61        with freeze_time(at + timedelta(days=1)):
62            event.save()
63            event_post_save_activity(Event, event, created=True, raw=True)
64        self.assertEqual(UserActivity.objects.get(user=admin).last_activity_at, at)
65
66    def test_backfill_matches_attribution_and_preserves_newer_activity(self):
67        users = [create_test_user() for _ in range(3)]
68        at = now() - timedelta(days=2)
69        with patch("authentik.events.signals.UserActivity.objects.record"):
70            for index, action in enumerate(
71                (EventAction.LOGIN, EventAction.AUTHORIZE_APPLICATION, EventAction.LOGIN_FAILED)
72            ):
73                with freeze_time(at):
74                    Event.new(action).set_user(users[index]).save()
75            event = Event.new(EventAction.LOGIN)
76            event.user = {"pk": "invalid", "on_behalf_of": {"pk": users[2].pk}}
77            event.save()
78        UserActivity.objects.record(users[0].pk)
79        current = UserActivity.objects.get(user=users[0]).last_activity_at
80        migration = import_module("authentik.core.migrations.0069_useractivity")
81        with connection.cursor() as cursor:
82            cursor.execute(migration.Migration.operations[-1].sql)
83        self.assertEqual(UserActivity.objects.get(user=users[0]).last_activity_at, current)
84        self.assertEqual(UserActivity.objects.get(user=users[1]).last_activity_at, at)
85        self.assertFalse(UserActivity.objects.filter(user=users[2]).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.

def test_monotonic_throttle_boundaries_and_invalid_ids(self):
22    def test_monotonic_throttle_boundaries_and_invalid_ids(self):
23        user = create_test_user()
24        at = now()
25        UserActivity.objects.record(user.pk, at)
26        for delta in (-timedelta(days=1), USER_ACTIVITY_INTERVAL - timedelta(microseconds=1)):
27            UserActivity.objects.record(user.pk, at + delta)
28            self.assertEqual(UserActivity.objects.get(user=user).last_activity_at, at)
29        UserActivity.objects.record(user.pk, at + USER_ACTIVITY_INTERVAL)
30        self.assertEqual(
31            UserActivity.objects.get(user=user).last_activity_at, at + USER_ACTIVITY_INTERVAL
32        )
33        user.delete()
34        for invalid in (None, "1", True, 10**100):
35            UserActivity.objects.record(invalid, at)
36        self.assertFalse(UserActivity.objects.exists())
def test_late_activity_for_deleted_user_is_allowed(self):
38    def test_late_activity_for_deleted_user_is_allowed(self):
39        user = create_test_user()
40        user_id = user.pk
41        UserActivity.objects.record(user_id)
42        user.delete()
43        self.assertFalse(UserActivity.objects.filter(user_id=user_id).exists())
44        UserActivity.objects.record(user_id)
45        self.assertTrue(UserActivity.objects.filter(user_id=user_id).exists())
def test_record_writes_to_primary_with_read_replicas(self):
47    def test_record_writes_to_primary_with_read_replicas(self):
48        user = create_test_user()
49        with patch("authentik.root.db.router.FailoverRouter.db_for_read", return_value="replica"):
50            UserActivity.objects.record(user.pk)
51        self.assertTrue(UserActivity.objects.filter(user=user).exists())
def test_event_attribution_and_resaves(self):
53    def test_event_attribution_and_resaves(self):
54        admin, target = create_test_user(), create_test_user()
55        at = now()
56        with freeze_time(at):
57            event = Event.new(EventAction.LOGIN)
58            event.user = {"pk": admin.pk, "on_behalf_of": {"pk": target.pk}}
59            event.save()
60        self.assertFalse(UserActivity.objects.filter(user=target).exists())
61        with freeze_time(at + timedelta(days=1)):
62            event.save()
63            event_post_save_activity(Event, event, created=True, raw=True)
64        self.assertEqual(UserActivity.objects.get(user=admin).last_activity_at, at)
def test_backfill_matches_attribution_and_preserves_newer_activity(self):
66    def test_backfill_matches_attribution_and_preserves_newer_activity(self):
67        users = [create_test_user() for _ in range(3)]
68        at = now() - timedelta(days=2)
69        with patch("authentik.events.signals.UserActivity.objects.record"):
70            for index, action in enumerate(
71                (EventAction.LOGIN, EventAction.AUTHORIZE_APPLICATION, EventAction.LOGIN_FAILED)
72            ):
73                with freeze_time(at):
74                    Event.new(action).set_user(users[index]).save()
75            event = Event.new(EventAction.LOGIN)
76            event.user = {"pk": "invalid", "on_behalf_of": {"pk": users[2].pk}}
77            event.save()
78        UserActivity.objects.record(users[0].pk)
79        current = UserActivity.objects.get(user=users[0]).last_activity_at
80        migration = import_module("authentik.core.migrations.0069_useractivity")
81        with connection.cursor() as cursor:
82            cursor.execute(migration.Migration.operations[-1].sql)
83        self.assertEqual(UserActivity.objects.get(user=users[0]).last_activity_at, current)
84        self.assertEqual(UserActivity.objects.get(user=users[1]).last_activity_at, at)
85        self.assertFalse(UserActivity.objects.filter(user=users[2]).exists())
class TestConcurrentActivityRecording(django.test.testcases.TransactionTestCase):
 88class TestConcurrentActivityRecording(TransactionTestCase):
 89    def test_concurrent_first_writes_keep_the_newest_timestamp(self):
 90        user = create_test_user()
 91        at = now()
 92        barrier = Barrier(2)
 93
 94        def record(timestamp):
 95            close_old_connections()
 96            try:
 97                with connection.cursor() as cursor:
 98                    cursor.execute("SET statement_timeout = '10s'")
 99                barrier.wait(timeout=5)
100                UserActivity.objects.record(user.pk, timestamp)
101            finally:
102                connection.close()
103
104        with ThreadPoolExecutor(max_workers=2) as pool:
105            futures = [
106                pool.submit(record, timestamp) for timestamp in (at, at + USER_ACTIVITY_INTERVAL)
107            ]
108            try:
109                for future in futures:
110                    future.result(timeout=15)
111            finally:
112                barrier.abort()
113        self.assertEqual(
114            UserActivity.objects.get(user=user).last_activity_at, at + USER_ACTIVITY_INTERVAL
115        )

A class whose instances are single test cases.

By default, the test code itself should be placed in a method named 'runTest'.

If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute.

Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively.

If it is necessary to override the __init__ method, the base class __init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by parts of the framework in order to be run.

When subclassing TestCase, you can set these attributes:

  • failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'.
  • longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in addition to any explicit message passed.
  • maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required.
def test_concurrent_first_writes_keep_the_newest_timestamp(self):
 89    def test_concurrent_first_writes_keep_the_newest_timestamp(self):
 90        user = create_test_user()
 91        at = now()
 92        barrier = Barrier(2)
 93
 94        def record(timestamp):
 95            close_old_connections()
 96            try:
 97                with connection.cursor() as cursor:
 98                    cursor.execute("SET statement_timeout = '10s'")
 99                barrier.wait(timeout=5)
100                UserActivity.objects.record(user.pk, timestamp)
101            finally:
102                connection.close()
103
104        with ThreadPoolExecutor(max_workers=2) as pool:
105            futures = [
106                pool.submit(record, timestamp) for timestamp in (at, at + USER_ACTIVITY_INTERVAL)
107            ]
108            try:
109                for future in futures:
110                    future.result(timeout=15)
111            finally:
112                barrier.abort()
113        self.assertEqual(
114            UserActivity.objects.get(user=user).last_activity_at, at + USER_ACTIVITY_INTERVAL
115        )