authentik.recovery.tests

recovery tests

  1"""recovery tests"""
  2
  3from datetime import timedelta
  4from io import StringIO
  5
  6from django.core.management import call_command
  7from django.test import TestCase
  8from django.urls import reverse
  9from django.utils.timezone import now
 10
 11from authentik.brands.models import SESSION_KEY_BRAND_SAFE_MODE
 12from authentik.core.models import Token, TokenIntents, User
 13
 14
 15class TestRecovery(TestCase):
 16    """recovery tests"""
 17
 18    def setUp(self):
 19        self.user: User = User.objects.create_user(username="recovery-test-user")
 20
 21    def test_create_key(self):
 22        """Test creation of a new key"""
 23        out = StringIO()
 24        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 0)
 25        call_command(
 26            "create_recovery_key",
 27            "5",
 28            self.user.username,
 29            stdout=out,
 30        )
 31        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
 32        self.assertIn(token.key, out.getvalue())
 33        self.assertIn("valid for 5\xa0minutes", out.getvalue())
 34        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 1)
 35
 36    def test_create_key_invalid(self):
 37        """Test creation of a new key (invalid)"""
 38        out = StringIO()
 39        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 0)
 40        call_command("create_recovery_key", "5", "foo", stderr=out)
 41        self.assertIn("not found", out.getvalue())
 42
 43    def test_recovery_view(self):
 44        """Test recovery view"""
 45        out = StringIO()
 46        call_command(
 47            "create_recovery_key",
 48            "10",
 49            self.user.username,
 50            stdout=out,
 51        )
 52        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
 53        self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": token.key}))
 54        self.assertEqual(self.client.session["authenticatedsession"].user.pk, token.user.pk)
 55
 56    def test_recovery_view_safe_mode(self):
 57        """Test recovery view enables brand safe mode on the session"""
 58        out = StringIO()
 59        call_command(
 60            "create_recovery_key",
 61            "10",
 62            self.user.username,
 63            stdout=out,
 64        )
 65        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
 66        self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": token.key}))
 67        self.assertTrue(self.client.session[SESSION_KEY_BRAND_SAFE_MODE])
 68
 69    def test_recovery_view_invalid(self):
 70        """Test recovery view with invalid token"""
 71        response = self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": "abc"}))
 72        self.assertEqual(response.status_code, 404)
 73
 74    def test_recovery_admin_group_invalid(self):
 75        """Test creation of admin group"""
 76        out = StringIO()
 77        call_command("create_admin_group", "1", stderr=out)
 78        self.assertIn("not found", out.getvalue())
 79
 80    def test_recovery_admin_group(self):
 81        """Test creation of admin group"""
 82        out = StringIO()
 83        call_command("create_admin_group", self.user.username, stdout=out)
 84        self.assertIn("successfully added to", out.getvalue())
 85        self.assertTrue(self.user.is_superuser)
 86
 87    def test_create_key_default_duration(self):
 88        """Test creation of a new key with default duration (60 minutes)"""
 89        out = StringIO()
 90        before_creation = now()
 91        call_command(
 92            "create_recovery_key",
 93            self.user.username,
 94            stdout=out,
 95        )
 96        after_creation = now()
 97
 98        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
 99        self.assertIn(token.key, out.getvalue())
100        self.assertIn("valid for 1\xa0hour", out.getvalue())
101
102        # Verify the token expires in approximately 60 minutes (default)
103        expected_expiry_min = before_creation + timedelta(minutes=60)
104        expected_expiry_max = after_creation + timedelta(minutes=60)
105        self.assertGreaterEqual(token.expires, expected_expiry_min)
106        self.assertLessEqual(token.expires, expected_expiry_max)
107
108    def test_create_key_custom_duration(self):
109        """Test creation of a new key with custom duration"""
110        out = StringIO()
111        custom_duration = 120  # 2 hours
112        before_creation = now()
113
114        call_command(
115            "create_recovery_key",
116            str(custom_duration),
117            self.user.username,
118            stdout=out,
119        )
120        after_creation = now()
121
122        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
123        self.assertIn(token.key, out.getvalue())
124        self.assertIn("valid for 2\xa0hours", out.getvalue())
125
126        # Verify the token expires in approximately the custom duration
127        expected_expiry_min = before_creation + timedelta(minutes=custom_duration)
128        expected_expiry_max = after_creation + timedelta(minutes=custom_duration)
129        self.assertGreaterEqual(token.expires, expected_expiry_min)
130        self.assertLessEqual(token.expires, expected_expiry_max)
131
132    def test_create_key_short_duration(self):
133        """Test creation of a new key with very short duration (1 minute)"""
134        out = StringIO()
135        short_duration = 1
136        before_creation = now()
137
138        call_command(
139            "create_recovery_key",
140            str(short_duration),
141            self.user.username,
142            stdout=out,
143        )
144        after_creation = now()
145
146        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
147        self.assertIn(token.key, out.getvalue())
148        self.assertIn("valid for 1\xa0minute", out.getvalue())
149
150        # Verify the token expires in approximately 1 minute
151        expected_expiry_min = before_creation + timedelta(minutes=short_duration)
152        expected_expiry_max = after_creation + timedelta(minutes=short_duration)
153        self.assertGreaterEqual(token.expires, expected_expiry_min)
154        self.assertLessEqual(token.expires, expected_expiry_max)
155
156    def test_create_key_duration_validation(self):
157        """Test that the duration is correctly converted to minutes"""
158        # Test various durations to ensure they're calculated correctly
159        test_cases = [1, 5, 30, 60, 120, 1440]  # 1min, 5min, 30min, 1hr, 2hr, 24hr
160
161        for duration in test_cases:
162            with self.subTest(duration=duration):
163                out = StringIO()
164                before_creation = now()
165
166                call_command(
167                    "create_recovery_key",
168                    str(duration),
169                    self.user.username,
170                    stdout=out,
171                )
172                after_creation = now()
173
174                token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
175
176                # Verify the token expires in approximately the specified duration
177                expected_expiry_min = before_creation + timedelta(minutes=duration)
178                expected_expiry_max = after_creation + timedelta(minutes=duration)
179                self.assertGreaterEqual(token.expires, expected_expiry_min)
180                self.assertLessEqual(token.expires, expected_expiry_max)
181
182                # Clean up for next iteration
183                token.delete()
184
185    def test_create_key_help_text(self):
186        """Test that the help text correctly indicates minutes"""
187        from authentik.recovery.management.commands.create_recovery_key import Command
188
189        command = Command()
190        # Check that the help text mentions minutes
191        parser = command.create_parser("test", "create_recovery_key")
192        help_text = parser.format_help()
193        self.assertIn("minutes", help_text.lower())
194        self.assertNotIn("years", help_text.lower())
class TestRecovery(django.test.testcases.TestCase):
 16class TestRecovery(TestCase):
 17    """recovery tests"""
 18
 19    def setUp(self):
 20        self.user: User = User.objects.create_user(username="recovery-test-user")
 21
 22    def test_create_key(self):
 23        """Test creation of a new key"""
 24        out = StringIO()
 25        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 0)
 26        call_command(
 27            "create_recovery_key",
 28            "5",
 29            self.user.username,
 30            stdout=out,
 31        )
 32        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
 33        self.assertIn(token.key, out.getvalue())
 34        self.assertIn("valid for 5\xa0minutes", out.getvalue())
 35        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 1)
 36
 37    def test_create_key_invalid(self):
 38        """Test creation of a new key (invalid)"""
 39        out = StringIO()
 40        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 0)
 41        call_command("create_recovery_key", "5", "foo", stderr=out)
 42        self.assertIn("not found", out.getvalue())
 43
 44    def test_recovery_view(self):
 45        """Test recovery view"""
 46        out = StringIO()
 47        call_command(
 48            "create_recovery_key",
 49            "10",
 50            self.user.username,
 51            stdout=out,
 52        )
 53        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
 54        self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": token.key}))
 55        self.assertEqual(self.client.session["authenticatedsession"].user.pk, token.user.pk)
 56
 57    def test_recovery_view_safe_mode(self):
 58        """Test recovery view enables brand safe mode on the session"""
 59        out = StringIO()
 60        call_command(
 61            "create_recovery_key",
 62            "10",
 63            self.user.username,
 64            stdout=out,
 65        )
 66        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
 67        self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": token.key}))
 68        self.assertTrue(self.client.session[SESSION_KEY_BRAND_SAFE_MODE])
 69
 70    def test_recovery_view_invalid(self):
 71        """Test recovery view with invalid token"""
 72        response = self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": "abc"}))
 73        self.assertEqual(response.status_code, 404)
 74
 75    def test_recovery_admin_group_invalid(self):
 76        """Test creation of admin group"""
 77        out = StringIO()
 78        call_command("create_admin_group", "1", stderr=out)
 79        self.assertIn("not found", out.getvalue())
 80
 81    def test_recovery_admin_group(self):
 82        """Test creation of admin group"""
 83        out = StringIO()
 84        call_command("create_admin_group", self.user.username, stdout=out)
 85        self.assertIn("successfully added to", out.getvalue())
 86        self.assertTrue(self.user.is_superuser)
 87
 88    def test_create_key_default_duration(self):
 89        """Test creation of a new key with default duration (60 minutes)"""
 90        out = StringIO()
 91        before_creation = now()
 92        call_command(
 93            "create_recovery_key",
 94            self.user.username,
 95            stdout=out,
 96        )
 97        after_creation = now()
 98
 99        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
100        self.assertIn(token.key, out.getvalue())
101        self.assertIn("valid for 1\xa0hour", out.getvalue())
102
103        # Verify the token expires in approximately 60 minutes (default)
104        expected_expiry_min = before_creation + timedelta(minutes=60)
105        expected_expiry_max = after_creation + timedelta(minutes=60)
106        self.assertGreaterEqual(token.expires, expected_expiry_min)
107        self.assertLessEqual(token.expires, expected_expiry_max)
108
109    def test_create_key_custom_duration(self):
110        """Test creation of a new key with custom duration"""
111        out = StringIO()
112        custom_duration = 120  # 2 hours
113        before_creation = now()
114
115        call_command(
116            "create_recovery_key",
117            str(custom_duration),
118            self.user.username,
119            stdout=out,
120        )
121        after_creation = now()
122
123        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
124        self.assertIn(token.key, out.getvalue())
125        self.assertIn("valid for 2\xa0hours", out.getvalue())
126
127        # Verify the token expires in approximately the custom duration
128        expected_expiry_min = before_creation + timedelta(minutes=custom_duration)
129        expected_expiry_max = after_creation + timedelta(minutes=custom_duration)
130        self.assertGreaterEqual(token.expires, expected_expiry_min)
131        self.assertLessEqual(token.expires, expected_expiry_max)
132
133    def test_create_key_short_duration(self):
134        """Test creation of a new key with very short duration (1 minute)"""
135        out = StringIO()
136        short_duration = 1
137        before_creation = now()
138
139        call_command(
140            "create_recovery_key",
141            str(short_duration),
142            self.user.username,
143            stdout=out,
144        )
145        after_creation = now()
146
147        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
148        self.assertIn(token.key, out.getvalue())
149        self.assertIn("valid for 1\xa0minute", out.getvalue())
150
151        # Verify the token expires in approximately 1 minute
152        expected_expiry_min = before_creation + timedelta(minutes=short_duration)
153        expected_expiry_max = after_creation + timedelta(minutes=short_duration)
154        self.assertGreaterEqual(token.expires, expected_expiry_min)
155        self.assertLessEqual(token.expires, expected_expiry_max)
156
157    def test_create_key_duration_validation(self):
158        """Test that the duration is correctly converted to minutes"""
159        # Test various durations to ensure they're calculated correctly
160        test_cases = [1, 5, 30, 60, 120, 1440]  # 1min, 5min, 30min, 1hr, 2hr, 24hr
161
162        for duration in test_cases:
163            with self.subTest(duration=duration):
164                out = StringIO()
165                before_creation = now()
166
167                call_command(
168                    "create_recovery_key",
169                    str(duration),
170                    self.user.username,
171                    stdout=out,
172                )
173                after_creation = now()
174
175                token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
176
177                # Verify the token expires in approximately the specified duration
178                expected_expiry_min = before_creation + timedelta(minutes=duration)
179                expected_expiry_max = after_creation + timedelta(minutes=duration)
180                self.assertGreaterEqual(token.expires, expected_expiry_min)
181                self.assertLessEqual(token.expires, expected_expiry_max)
182
183                # Clean up for next iteration
184                token.delete()
185
186    def test_create_key_help_text(self):
187        """Test that the help text correctly indicates minutes"""
188        from authentik.recovery.management.commands.create_recovery_key import Command
189
190        command = Command()
191        # Check that the help text mentions minutes
192        parser = command.create_parser("test", "create_recovery_key")
193        help_text = parser.format_help()
194        self.assertIn("minutes", help_text.lower())
195        self.assertNotIn("years", help_text.lower())

recovery tests

def setUp(self):
19    def setUp(self):
20        self.user: User = User.objects.create_user(username="recovery-test-user")

Hook method for setting up the test fixture before exercising it.

def test_create_key(self):
22    def test_create_key(self):
23        """Test creation of a new key"""
24        out = StringIO()
25        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 0)
26        call_command(
27            "create_recovery_key",
28            "5",
29            self.user.username,
30            stdout=out,
31        )
32        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
33        self.assertIn(token.key, out.getvalue())
34        self.assertIn("valid for 5\xa0minutes", out.getvalue())
35        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 1)

Test creation of a new key

def test_create_key_invalid(self):
37    def test_create_key_invalid(self):
38        """Test creation of a new key (invalid)"""
39        out = StringIO()
40        self.assertEqual(len(Token.objects.filter(intent=TokenIntents.INTENT_RECOVERY)), 0)
41        call_command("create_recovery_key", "5", "foo", stderr=out)
42        self.assertIn("not found", out.getvalue())

Test creation of a new key (invalid)

def test_recovery_view(self):
44    def test_recovery_view(self):
45        """Test recovery view"""
46        out = StringIO()
47        call_command(
48            "create_recovery_key",
49            "10",
50            self.user.username,
51            stdout=out,
52        )
53        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
54        self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": token.key}))
55        self.assertEqual(self.client.session["authenticatedsession"].user.pk, token.user.pk)

Test recovery view

def test_recovery_view_safe_mode(self):
57    def test_recovery_view_safe_mode(self):
58        """Test recovery view enables brand safe mode on the session"""
59        out = StringIO()
60        call_command(
61            "create_recovery_key",
62            "10",
63            self.user.username,
64            stdout=out,
65        )
66        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
67        self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": token.key}))
68        self.assertTrue(self.client.session[SESSION_KEY_BRAND_SAFE_MODE])

Test recovery view enables brand safe mode on the session

def test_recovery_view_invalid(self):
70    def test_recovery_view_invalid(self):
71        """Test recovery view with invalid token"""
72        response = self.client.get(reverse("authentik_recovery:use-token", kwargs={"key": "abc"}))
73        self.assertEqual(response.status_code, 404)

Test recovery view with invalid token

def test_recovery_admin_group_invalid(self):
75    def test_recovery_admin_group_invalid(self):
76        """Test creation of admin group"""
77        out = StringIO()
78        call_command("create_admin_group", "1", stderr=out)
79        self.assertIn("not found", out.getvalue())

Test creation of admin group

def test_recovery_admin_group(self):
81    def test_recovery_admin_group(self):
82        """Test creation of admin group"""
83        out = StringIO()
84        call_command("create_admin_group", self.user.username, stdout=out)
85        self.assertIn("successfully added to", out.getvalue())
86        self.assertTrue(self.user.is_superuser)

Test creation of admin group

def test_create_key_default_duration(self):
 88    def test_create_key_default_duration(self):
 89        """Test creation of a new key with default duration (60 minutes)"""
 90        out = StringIO()
 91        before_creation = now()
 92        call_command(
 93            "create_recovery_key",
 94            self.user.username,
 95            stdout=out,
 96        )
 97        after_creation = now()
 98
 99        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
100        self.assertIn(token.key, out.getvalue())
101        self.assertIn("valid for 1\xa0hour", out.getvalue())
102
103        # Verify the token expires in approximately 60 minutes (default)
104        expected_expiry_min = before_creation + timedelta(minutes=60)
105        expected_expiry_max = after_creation + timedelta(minutes=60)
106        self.assertGreaterEqual(token.expires, expected_expiry_min)
107        self.assertLessEqual(token.expires, expected_expiry_max)

Test creation of a new key with default duration (60 minutes)

def test_create_key_custom_duration(self):
109    def test_create_key_custom_duration(self):
110        """Test creation of a new key with custom duration"""
111        out = StringIO()
112        custom_duration = 120  # 2 hours
113        before_creation = now()
114
115        call_command(
116            "create_recovery_key",
117            str(custom_duration),
118            self.user.username,
119            stdout=out,
120        )
121        after_creation = now()
122
123        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
124        self.assertIn(token.key, out.getvalue())
125        self.assertIn("valid for 2\xa0hours", out.getvalue())
126
127        # Verify the token expires in approximately the custom duration
128        expected_expiry_min = before_creation + timedelta(minutes=custom_duration)
129        expected_expiry_max = after_creation + timedelta(minutes=custom_duration)
130        self.assertGreaterEqual(token.expires, expected_expiry_min)
131        self.assertLessEqual(token.expires, expected_expiry_max)

Test creation of a new key with custom duration

def test_create_key_short_duration(self):
133    def test_create_key_short_duration(self):
134        """Test creation of a new key with very short duration (1 minute)"""
135        out = StringIO()
136        short_duration = 1
137        before_creation = now()
138
139        call_command(
140            "create_recovery_key",
141            str(short_duration),
142            self.user.username,
143            stdout=out,
144        )
145        after_creation = now()
146
147        token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
148        self.assertIn(token.key, out.getvalue())
149        self.assertIn("valid for 1\xa0minute", out.getvalue())
150
151        # Verify the token expires in approximately 1 minute
152        expected_expiry_min = before_creation + timedelta(minutes=short_duration)
153        expected_expiry_max = after_creation + timedelta(minutes=short_duration)
154        self.assertGreaterEqual(token.expires, expected_expiry_min)
155        self.assertLessEqual(token.expires, expected_expiry_max)

Test creation of a new key with very short duration (1 minute)

def test_create_key_duration_validation(self):
157    def test_create_key_duration_validation(self):
158        """Test that the duration is correctly converted to minutes"""
159        # Test various durations to ensure they're calculated correctly
160        test_cases = [1, 5, 30, 60, 120, 1440]  # 1min, 5min, 30min, 1hr, 2hr, 24hr
161
162        for duration in test_cases:
163            with self.subTest(duration=duration):
164                out = StringIO()
165                before_creation = now()
166
167                call_command(
168                    "create_recovery_key",
169                    str(duration),
170                    self.user.username,
171                    stdout=out,
172                )
173                after_creation = now()
174
175                token = Token.objects.get(intent=TokenIntents.INTENT_RECOVERY, user=self.user)
176
177                # Verify the token expires in approximately the specified duration
178                expected_expiry_min = before_creation + timedelta(minutes=duration)
179                expected_expiry_max = after_creation + timedelta(minutes=duration)
180                self.assertGreaterEqual(token.expires, expected_expiry_min)
181                self.assertLessEqual(token.expires, expected_expiry_max)
182
183                # Clean up for next iteration
184                token.delete()

Test that the duration is correctly converted to minutes

def test_create_key_help_text(self):
186    def test_create_key_help_text(self):
187        """Test that the help text correctly indicates minutes"""
188        from authentik.recovery.management.commands.create_recovery_key import Command
189
190        command = Command()
191        # Check that the help text mentions minutes
192        parser = command.create_parser("test", "create_recovery_key")
193        help_text = parser.format_help()
194        self.assertIn("minutes", help_text.lower())
195        self.assertNotIn("years", help_text.lower())

Test that the help text correctly indicates minutes