authentik.sources.telegram.tests

Telegram source tests

  1"""Telegram source tests"""
  2
  3import hashlib
  4import hmac
  5from datetime import datetime, timedelta
  6from unittest.mock import Mock
  7
  8from django.test import TestCase
  9from django.urls import reverse
 10from rest_framework.exceptions import ValidationError
 11
 12from authentik.core.tests.utils import create_test_flow, create_test_user
 13from authentik.flows.models import FlowDesignation, FlowStageBinding
 14from authentik.flows.planner import PLAN_CONTEXT_REDIRECT, FlowPlan
 15from authentik.flows.tests import APIFlowTestCase
 16from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET, SESSION_KEY_PLAN
 17from authentik.lib.generators import generate_id
 18from authentik.sources.telegram.models import UserTelegramSourceConnection
 19from authentik.sources.telegram.stage import TelegramChallengeResponse
 20from authentik.stages.identification.models import IdentificationStage, UserFields
 21
 22
 23class MockTelegramResponseMixin:
 24    def _add_hash(self, response):
 25        to_hash = "\n".join([f"{key}={value}" for key, value in sorted(response.items())])
 26        response["hash"] = hmac.new(
 27            hashlib.sha256(self.source.bot_token.encode("utf-8")).digest(),
 28            to_hash.encode("utf-8"),
 29            "sha256",
 30        ).hexdigest()
 31
 32    def _make_valid_response(self):
 33        resp = {
 34            "id": "123456789",
 35            "first_name": "Test",
 36            "last_name": "User",
 37            "username": "testuser",
 38            "auth_date": str(int(datetime.now().timestamp())),
 39        }
 40        self._add_hash(resp)
 41        return resp
 42
 43    def _make_outdated_response(self):
 44        resp = self._make_valid_response()
 45        resp["auth_date"] = str(int((datetime.now() - timedelta(days=1)).timestamp()))
 46        self._add_hash(resp)
 47        return resp
 48
 49
 50class TestTelegramSource(MockTelegramResponseMixin, TestCase):
 51    """Telegram Source tests"""
 52
 53    def setUp(self):
 54        from authentik.sources.telegram.models import TelegramSource
 55
 56        self.source = TelegramSource.objects.create(
 57            name="test",
 58            slug="test",
 59            bot_username="test_bot",
 60            bot_token="modern_token",  # nosec
 61            request_message_access=True,
 62            pre_authentication_flow=create_test_flow(),
 63        )
 64        self.mock_stage = Mock()
 65        self.mock_stage.source = self.source
 66
 67    def test_ui_login_button(self):
 68        """Test UI login button"""
 69        ui_login_button = self.source.ui_login_button(None)
 70        self.assertIsNotNone(ui_login_button)
 71        self.assertEqual(ui_login_button.name, "test")
 72        self.assertTrue(ui_login_button.challenge.is_valid(raise_exception=True))
 73
 74    def test_challenge_response(self):
 75        """Test correct Telegram response validation"""
 76        cr = TelegramChallengeResponse(data=self._make_valid_response())
 77        cr.stage = self.mock_stage
 78        self.assertTrue(cr.is_valid(raise_exception=True))
 79
 80    def test_outdated_challenge_response(self):
 81        """Test outdated Telegram response validation"""
 82        cr = TelegramChallengeResponse(data=self._make_outdated_response())
 83        cr.stage = self.mock_stage
 84        with self.assertRaises(ValidationError):
 85            cr.is_valid(raise_exception=True)
 86
 87    def test_invalid_hash_challenge_response(self):
 88        """Test invalid hash in Telegram response validation"""
 89        resp = self._make_valid_response()
 90        resp["hash"] = "invalid_hash"
 91        cr = TelegramChallengeResponse(data=resp)
 92        cr.stage = self.mock_stage
 93        with self.assertRaises(ValidationError):
 94            cr.is_valid(raise_exception=True)
 95
 96    def test_user_base_properties(self):
 97        """Test user base properties"""
 98        cr = TelegramChallengeResponse(data=self._make_valid_response())
 99        cr.stage = self.mock_stage
100        cr.is_valid(raise_exception=True)
101        properties = self.source.get_base_user_properties(info=cr.validated_data)
102        self.assertEqual(
103            properties,
104            {
105                "username": "testuser",
106                "name": "Test User",
107                "email": None,
108            },
109        )
110
111    def test_group_base_properties(self):
112        """Test group base properties"""
113        for group_id in ["group 1", "group 2"]:
114            properties = self.source.get_base_group_properties(group_id=group_id)
115            self.assertEqual(properties, {"name": group_id})
116
117
118class TestTelegramViews(MockTelegramResponseMixin, APIFlowTestCase):
119    """Test Telegram source views"""
120
121    def setUp(self):
122        super().setUp()
123        from authentik.sources.telegram.models import TelegramSource
124
125        self.pre_auth_flow = create_test_flow()
126
127        self.source = TelegramSource.objects.create(
128            name="test",
129            slug="test",
130            bot_username="test_bot",
131            bot_token="modern_token",  # nosec
132            request_message_access=True,
133            enrollment_flow=create_test_flow(),
134            pre_authentication_flow=self.pre_auth_flow,
135        )
136
137        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
138        self.stage = IdentificationStage.objects.create(
139            name="identification",
140            user_fields=[UserFields.E_MAIL],
141            pretend_user_exists=False,
142        )
143        self.stage.sources.set([self.source])
144        self.stage.save()
145        FlowStageBinding.objects.create(
146            target=self.flow,
147            stage=self.stage,
148            order=0,
149        )
150
151    def _make_initial_request(self):
152        return self.client.get(
153            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
154        )
155
156    def _make_start_request(self):
157        return self.client.get(
158            reverse("authentik_sources_telegram:start", kwargs={"source_slug": self.source.slug}),
159            follow=True,
160        )
161
162    def test_start_view(self):
163        """Test TelegramStartView"""
164        self.assertEqual(self._make_initial_request().status_code, 200)
165
166        response = self._make_start_request()
167        self.assertEqual(response.status_code, 200)
168        self.assertEqual(
169            response.redirect_chain[0][0],
170            reverse("authentik_core:if-flow", kwargs={"flow_slug": self.pre_auth_flow.slug}),
171        )
172
173    def test_challenge_view(self):
174        """Test TelegramLoginView"""
175        self._make_initial_request()
176        self._make_start_request()
177        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.pre_auth_flow.slug})
178        get_response = self.client.get(url)
179        self.assertEqual(get_response.status_code, 200)
180        form_data = self._make_valid_response()
181        form_data["component"] = "ak-source-telegram"
182        response = self.client.post(url, form_data)
183        self.assertEqual(response.status_code, 200)
184        self.assertStageRedirects(
185            response,
186            reverse(
187                "authentik_core:if-flow", kwargs={"flow_slug": self.source.enrollment_flow.slug}
188            ),
189        )
190
191    def test_challenge_view_preserves_next_redirect(self):
192        """Regression test for #18450: completing Telegram auth must preserve the OIDC
193        redirect_uri so the user returns to the application instead of /if/user/.
194
195        Root cause: the pre_authentication_flow executor overwrites SESSION_KEY_GET with
196        an empty dict (its redirect URL has no query string), losing the original next=
197        parameter. The fix reads PLAN_CONTEXT_REDIRECT from the executor plan context —
198        where TelegramStartView saved it before the overwrite — and restores SESSION_KEY_GET.
199        """
200        initial_redirect = f"http://{generate_id()}"
201
202        self._make_initial_request()
203
204        # Simulate SESSION_KEY_GET as set by the flow executor when the user arrives
205        # from an OIDC authorization request (e.g. next=/application/o/authorize/?...).
206        session = self.client.session
207        session[SESSION_KEY_GET] = {NEXT_ARG_NAME: initial_redirect}
208        session.save()
209
210        # TelegramStartView reads SESSION_KEY_GET and saves it as PLAN_CONTEXT_REDIRECT
211        # in the pre_authentication_flow plan, then redirects to that flow.
212        self._make_start_request()
213
214        # GET the pre_auth_flow executor. This runs FlowExecutorView.dispatch() which
215        # unconditionally overwrites SESSION_KEY_GET with an empty dict (the redirect URL
216        # from TelegramStartView carries no query string). PLAN_CONTEXT_REDIRECT in the
217        # plan is still intact at this point.
218        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.pre_auth_flow.slug})
219        self.client.get(url)
220
221        form_data = self._make_valid_response()
222        form_data["component"] = "ak-source-telegram"
223        response = self.client.post(url, form_data)
224        self.assertEqual(response.status_code, 200)
225        self.assertStageRedirects(
226            response,
227            reverse(
228                "authentik_core:if-flow", kwargs={"flow_slug": self.source.enrollment_flow.slug}
229            ),
230        )
231
232        # The enrollment plan must carry PLAN_CONTEXT_REDIRECT so the user eventually
233        # reaches the application's callback URL rather than the default /if/user/.
234        plan: FlowPlan = self.client.session.get(SESSION_KEY_PLAN)
235        self.assertIsNotNone(plan)
236        self.assertEqual(plan.context.get(PLAN_CONTEXT_REDIRECT), initial_redirect)
237
238    def test_connect_user(self):
239        user = create_test_user("testuser")
240        user2 = create_test_user("testuser2")
241        self.client.force_login(user)
242        response = self.client.post(
243            reverse("authentik_api:telegramsource-connect-user", args=[self.source.slug]),
244            self._make_valid_response(),
245        )
246        self.assertEqual(response.status_code, 201)
247        self.assertTrue(
248            UserTelegramSourceConnection.objects.filter(user=user, source=self.source).exists()
249        )
250        self.client.logout()
251        self.client.force_login(user2)
252        response = self.client.post(
253            reverse("authentik_api:telegramsource-connect-user", args=[self.source.slug]),
254            self._make_valid_response(),
255        )
256        self.assertEqual(response.status_code, 403)
class MockTelegramResponseMixin:
24class MockTelegramResponseMixin:
25    def _add_hash(self, response):
26        to_hash = "\n".join([f"{key}={value}" for key, value in sorted(response.items())])
27        response["hash"] = hmac.new(
28            hashlib.sha256(self.source.bot_token.encode("utf-8")).digest(),
29            to_hash.encode("utf-8"),
30            "sha256",
31        ).hexdigest()
32
33    def _make_valid_response(self):
34        resp = {
35            "id": "123456789",
36            "first_name": "Test",
37            "last_name": "User",
38            "username": "testuser",
39            "auth_date": str(int(datetime.now().timestamp())),
40        }
41        self._add_hash(resp)
42        return resp
43
44    def _make_outdated_response(self):
45        resp = self._make_valid_response()
46        resp["auth_date"] = str(int((datetime.now() - timedelta(days=1)).timestamp()))
47        self._add_hash(resp)
48        return resp
class TestTelegramSource(MockTelegramResponseMixin, django.test.testcases.TestCase):
 51class TestTelegramSource(MockTelegramResponseMixin, TestCase):
 52    """Telegram Source tests"""
 53
 54    def setUp(self):
 55        from authentik.sources.telegram.models import TelegramSource
 56
 57        self.source = TelegramSource.objects.create(
 58            name="test",
 59            slug="test",
 60            bot_username="test_bot",
 61            bot_token="modern_token",  # nosec
 62            request_message_access=True,
 63            pre_authentication_flow=create_test_flow(),
 64        )
 65        self.mock_stage = Mock()
 66        self.mock_stage.source = self.source
 67
 68    def test_ui_login_button(self):
 69        """Test UI login button"""
 70        ui_login_button = self.source.ui_login_button(None)
 71        self.assertIsNotNone(ui_login_button)
 72        self.assertEqual(ui_login_button.name, "test")
 73        self.assertTrue(ui_login_button.challenge.is_valid(raise_exception=True))
 74
 75    def test_challenge_response(self):
 76        """Test correct Telegram response validation"""
 77        cr = TelegramChallengeResponse(data=self._make_valid_response())
 78        cr.stage = self.mock_stage
 79        self.assertTrue(cr.is_valid(raise_exception=True))
 80
 81    def test_outdated_challenge_response(self):
 82        """Test outdated Telegram response validation"""
 83        cr = TelegramChallengeResponse(data=self._make_outdated_response())
 84        cr.stage = self.mock_stage
 85        with self.assertRaises(ValidationError):
 86            cr.is_valid(raise_exception=True)
 87
 88    def test_invalid_hash_challenge_response(self):
 89        """Test invalid hash in Telegram response validation"""
 90        resp = self._make_valid_response()
 91        resp["hash"] = "invalid_hash"
 92        cr = TelegramChallengeResponse(data=resp)
 93        cr.stage = self.mock_stage
 94        with self.assertRaises(ValidationError):
 95            cr.is_valid(raise_exception=True)
 96
 97    def test_user_base_properties(self):
 98        """Test user base properties"""
 99        cr = TelegramChallengeResponse(data=self._make_valid_response())
100        cr.stage = self.mock_stage
101        cr.is_valid(raise_exception=True)
102        properties = self.source.get_base_user_properties(info=cr.validated_data)
103        self.assertEqual(
104            properties,
105            {
106                "username": "testuser",
107                "name": "Test User",
108                "email": None,
109            },
110        )
111
112    def test_group_base_properties(self):
113        """Test group base properties"""
114        for group_id in ["group 1", "group 2"]:
115            properties = self.source.get_base_group_properties(group_id=group_id)
116            self.assertEqual(properties, {"name": group_id})

Telegram Source tests

def setUp(self):
54    def setUp(self):
55        from authentik.sources.telegram.models import TelegramSource
56
57        self.source = TelegramSource.objects.create(
58            name="test",
59            slug="test",
60            bot_username="test_bot",
61            bot_token="modern_token",  # nosec
62            request_message_access=True,
63            pre_authentication_flow=create_test_flow(),
64        )
65        self.mock_stage = Mock()
66        self.mock_stage.source = self.source

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

def test_ui_login_button(self):
68    def test_ui_login_button(self):
69        """Test UI login button"""
70        ui_login_button = self.source.ui_login_button(None)
71        self.assertIsNotNone(ui_login_button)
72        self.assertEqual(ui_login_button.name, "test")
73        self.assertTrue(ui_login_button.challenge.is_valid(raise_exception=True))

Test UI login button

def test_challenge_response(self):
75    def test_challenge_response(self):
76        """Test correct Telegram response validation"""
77        cr = TelegramChallengeResponse(data=self._make_valid_response())
78        cr.stage = self.mock_stage
79        self.assertTrue(cr.is_valid(raise_exception=True))

Test correct Telegram response validation

def test_outdated_challenge_response(self):
81    def test_outdated_challenge_response(self):
82        """Test outdated Telegram response validation"""
83        cr = TelegramChallengeResponse(data=self._make_outdated_response())
84        cr.stage = self.mock_stage
85        with self.assertRaises(ValidationError):
86            cr.is_valid(raise_exception=True)

Test outdated Telegram response validation

def test_invalid_hash_challenge_response(self):
88    def test_invalid_hash_challenge_response(self):
89        """Test invalid hash in Telegram response validation"""
90        resp = self._make_valid_response()
91        resp["hash"] = "invalid_hash"
92        cr = TelegramChallengeResponse(data=resp)
93        cr.stage = self.mock_stage
94        with self.assertRaises(ValidationError):
95            cr.is_valid(raise_exception=True)

Test invalid hash in Telegram response validation

def test_user_base_properties(self):
 97    def test_user_base_properties(self):
 98        """Test user base properties"""
 99        cr = TelegramChallengeResponse(data=self._make_valid_response())
100        cr.stage = self.mock_stage
101        cr.is_valid(raise_exception=True)
102        properties = self.source.get_base_user_properties(info=cr.validated_data)
103        self.assertEqual(
104            properties,
105            {
106                "username": "testuser",
107                "name": "Test User",
108                "email": None,
109            },
110        )

Test user base properties

def test_group_base_properties(self):
112    def test_group_base_properties(self):
113        """Test group base properties"""
114        for group_id in ["group 1", "group 2"]:
115            properties = self.source.get_base_group_properties(group_id=group_id)
116            self.assertEqual(properties, {"name": group_id})

Test group base properties

class TestTelegramViews(MockTelegramResponseMixin, authentik.flows.tests.APIFlowTestCase):
119class TestTelegramViews(MockTelegramResponseMixin, APIFlowTestCase):
120    """Test Telegram source views"""
121
122    def setUp(self):
123        super().setUp()
124        from authentik.sources.telegram.models import TelegramSource
125
126        self.pre_auth_flow = create_test_flow()
127
128        self.source = TelegramSource.objects.create(
129            name="test",
130            slug="test",
131            bot_username="test_bot",
132            bot_token="modern_token",  # nosec
133            request_message_access=True,
134            enrollment_flow=create_test_flow(),
135            pre_authentication_flow=self.pre_auth_flow,
136        )
137
138        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
139        self.stage = IdentificationStage.objects.create(
140            name="identification",
141            user_fields=[UserFields.E_MAIL],
142            pretend_user_exists=False,
143        )
144        self.stage.sources.set([self.source])
145        self.stage.save()
146        FlowStageBinding.objects.create(
147            target=self.flow,
148            stage=self.stage,
149            order=0,
150        )
151
152    def _make_initial_request(self):
153        return self.client.get(
154            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
155        )
156
157    def _make_start_request(self):
158        return self.client.get(
159            reverse("authentik_sources_telegram:start", kwargs={"source_slug": self.source.slug}),
160            follow=True,
161        )
162
163    def test_start_view(self):
164        """Test TelegramStartView"""
165        self.assertEqual(self._make_initial_request().status_code, 200)
166
167        response = self._make_start_request()
168        self.assertEqual(response.status_code, 200)
169        self.assertEqual(
170            response.redirect_chain[0][0],
171            reverse("authentik_core:if-flow", kwargs={"flow_slug": self.pre_auth_flow.slug}),
172        )
173
174    def test_challenge_view(self):
175        """Test TelegramLoginView"""
176        self._make_initial_request()
177        self._make_start_request()
178        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.pre_auth_flow.slug})
179        get_response = self.client.get(url)
180        self.assertEqual(get_response.status_code, 200)
181        form_data = self._make_valid_response()
182        form_data["component"] = "ak-source-telegram"
183        response = self.client.post(url, form_data)
184        self.assertEqual(response.status_code, 200)
185        self.assertStageRedirects(
186            response,
187            reverse(
188                "authentik_core:if-flow", kwargs={"flow_slug": self.source.enrollment_flow.slug}
189            ),
190        )
191
192    def test_challenge_view_preserves_next_redirect(self):
193        """Regression test for #18450: completing Telegram auth must preserve the OIDC
194        redirect_uri so the user returns to the application instead of /if/user/.
195
196        Root cause: the pre_authentication_flow executor overwrites SESSION_KEY_GET with
197        an empty dict (its redirect URL has no query string), losing the original next=
198        parameter. The fix reads PLAN_CONTEXT_REDIRECT from the executor plan context —
199        where TelegramStartView saved it before the overwrite — and restores SESSION_KEY_GET.
200        """
201        initial_redirect = f"http://{generate_id()}"
202
203        self._make_initial_request()
204
205        # Simulate SESSION_KEY_GET as set by the flow executor when the user arrives
206        # from an OIDC authorization request (e.g. next=/application/o/authorize/?...).
207        session = self.client.session
208        session[SESSION_KEY_GET] = {NEXT_ARG_NAME: initial_redirect}
209        session.save()
210
211        # TelegramStartView reads SESSION_KEY_GET and saves it as PLAN_CONTEXT_REDIRECT
212        # in the pre_authentication_flow plan, then redirects to that flow.
213        self._make_start_request()
214
215        # GET the pre_auth_flow executor. This runs FlowExecutorView.dispatch() which
216        # unconditionally overwrites SESSION_KEY_GET with an empty dict (the redirect URL
217        # from TelegramStartView carries no query string). PLAN_CONTEXT_REDIRECT in the
218        # plan is still intact at this point.
219        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.pre_auth_flow.slug})
220        self.client.get(url)
221
222        form_data = self._make_valid_response()
223        form_data["component"] = "ak-source-telegram"
224        response = self.client.post(url, form_data)
225        self.assertEqual(response.status_code, 200)
226        self.assertStageRedirects(
227            response,
228            reverse(
229                "authentik_core:if-flow", kwargs={"flow_slug": self.source.enrollment_flow.slug}
230            ),
231        )
232
233        # The enrollment plan must carry PLAN_CONTEXT_REDIRECT so the user eventually
234        # reaches the application's callback URL rather than the default /if/user/.
235        plan: FlowPlan = self.client.session.get(SESSION_KEY_PLAN)
236        self.assertIsNotNone(plan)
237        self.assertEqual(plan.context.get(PLAN_CONTEXT_REDIRECT), initial_redirect)
238
239    def test_connect_user(self):
240        user = create_test_user("testuser")
241        user2 = create_test_user("testuser2")
242        self.client.force_login(user)
243        response = self.client.post(
244            reverse("authentik_api:telegramsource-connect-user", args=[self.source.slug]),
245            self._make_valid_response(),
246        )
247        self.assertEqual(response.status_code, 201)
248        self.assertTrue(
249            UserTelegramSourceConnection.objects.filter(user=user, source=self.source).exists()
250        )
251        self.client.logout()
252        self.client.force_login(user2)
253        response = self.client.post(
254            reverse("authentik_api:telegramsource-connect-user", args=[self.source.slug]),
255            self._make_valid_response(),
256        )
257        self.assertEqual(response.status_code, 403)

Test Telegram source views

def setUp(self):
122    def setUp(self):
123        super().setUp()
124        from authentik.sources.telegram.models import TelegramSource
125
126        self.pre_auth_flow = create_test_flow()
127
128        self.source = TelegramSource.objects.create(
129            name="test",
130            slug="test",
131            bot_username="test_bot",
132            bot_token="modern_token",  # nosec
133            request_message_access=True,
134            enrollment_flow=create_test_flow(),
135            pre_authentication_flow=self.pre_auth_flow,
136        )
137
138        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
139        self.stage = IdentificationStage.objects.create(
140            name="identification",
141            user_fields=[UserFields.E_MAIL],
142            pretend_user_exists=False,
143        )
144        self.stage.sources.set([self.source])
145        self.stage.save()
146        FlowStageBinding.objects.create(
147            target=self.flow,
148            stage=self.stage,
149            order=0,
150        )

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

def test_start_view(self):
163    def test_start_view(self):
164        """Test TelegramStartView"""
165        self.assertEqual(self._make_initial_request().status_code, 200)
166
167        response = self._make_start_request()
168        self.assertEqual(response.status_code, 200)
169        self.assertEqual(
170            response.redirect_chain[0][0],
171            reverse("authentik_core:if-flow", kwargs={"flow_slug": self.pre_auth_flow.slug}),
172        )

Test TelegramStartView

def test_challenge_view(self):
174    def test_challenge_view(self):
175        """Test TelegramLoginView"""
176        self._make_initial_request()
177        self._make_start_request()
178        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.pre_auth_flow.slug})
179        get_response = self.client.get(url)
180        self.assertEqual(get_response.status_code, 200)
181        form_data = self._make_valid_response()
182        form_data["component"] = "ak-source-telegram"
183        response = self.client.post(url, form_data)
184        self.assertEqual(response.status_code, 200)
185        self.assertStageRedirects(
186            response,
187            reverse(
188                "authentik_core:if-flow", kwargs={"flow_slug": self.source.enrollment_flow.slug}
189            ),
190        )

Test TelegramLoginView

def test_challenge_view_preserves_next_redirect(self):
192    def test_challenge_view_preserves_next_redirect(self):
193        """Regression test for #18450: completing Telegram auth must preserve the OIDC
194        redirect_uri so the user returns to the application instead of /if/user/.
195
196        Root cause: the pre_authentication_flow executor overwrites SESSION_KEY_GET with
197        an empty dict (its redirect URL has no query string), losing the original next=
198        parameter. The fix reads PLAN_CONTEXT_REDIRECT from the executor plan context —
199        where TelegramStartView saved it before the overwrite — and restores SESSION_KEY_GET.
200        """
201        initial_redirect = f"http://{generate_id()}"
202
203        self._make_initial_request()
204
205        # Simulate SESSION_KEY_GET as set by the flow executor when the user arrives
206        # from an OIDC authorization request (e.g. next=/application/o/authorize/?...).
207        session = self.client.session
208        session[SESSION_KEY_GET] = {NEXT_ARG_NAME: initial_redirect}
209        session.save()
210
211        # TelegramStartView reads SESSION_KEY_GET and saves it as PLAN_CONTEXT_REDIRECT
212        # in the pre_authentication_flow plan, then redirects to that flow.
213        self._make_start_request()
214
215        # GET the pre_auth_flow executor. This runs FlowExecutorView.dispatch() which
216        # unconditionally overwrites SESSION_KEY_GET with an empty dict (the redirect URL
217        # from TelegramStartView carries no query string). PLAN_CONTEXT_REDIRECT in the
218        # plan is still intact at this point.
219        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.pre_auth_flow.slug})
220        self.client.get(url)
221
222        form_data = self._make_valid_response()
223        form_data["component"] = "ak-source-telegram"
224        response = self.client.post(url, form_data)
225        self.assertEqual(response.status_code, 200)
226        self.assertStageRedirects(
227            response,
228            reverse(
229                "authentik_core:if-flow", kwargs={"flow_slug": self.source.enrollment_flow.slug}
230            ),
231        )
232
233        # The enrollment plan must carry PLAN_CONTEXT_REDIRECT so the user eventually
234        # reaches the application's callback URL rather than the default /if/user/.
235        plan: FlowPlan = self.client.session.get(SESSION_KEY_PLAN)
236        self.assertIsNotNone(plan)
237        self.assertEqual(plan.context.get(PLAN_CONTEXT_REDIRECT), initial_redirect)

Regression test for #18450: completing Telegram auth must preserve the OIDC redirect_uri so the user returns to the application instead of /if/user/.

Root cause: the pre_authentication_flow executor overwrites SESSION_KEY_GET with an empty dict (its redirect URL has no query string), losing the original next= parameter. The fix reads PLAN_CONTEXT_REDIRECT from the executor plan context — where TelegramStartView saved it before the overwrite — and restores SESSION_KEY_GET.

def test_connect_user(self):
239    def test_connect_user(self):
240        user = create_test_user("testuser")
241        user2 = create_test_user("testuser2")
242        self.client.force_login(user)
243        response = self.client.post(
244            reverse("authentik_api:telegramsource-connect-user", args=[self.source.slug]),
245            self._make_valid_response(),
246        )
247        self.assertEqual(response.status_code, 201)
248        self.assertTrue(
249            UserTelegramSourceConnection.objects.filter(user=user, source=self.source).exists()
250        )
251        self.client.logout()
252        self.client.force_login(user2)
253        response = self.client.post(
254            reverse("authentik_api:telegramsource-connect-user", args=[self.source.slug]),
255            self._make_valid_response(),
256        )
257        self.assertEqual(response.status_code, 403)