authentik.events.tests.test_transports

transport tests

  1"""transport tests"""
  2
  3from unittest.mock import PropertyMock, patch
  4
  5from django.core import mail
  6from django.core.mail.backends.locmem import EmailBackend
  7from django.test import TestCase
  8from django.urls import reverse
  9from requests_mock import Mocker
 10
 11from authentik import authentik_full_version
 12from authentik.core.tests.utils import create_test_admin_user
 13from authentik.crypto.models import CertificateKeyPair
 14from authentik.events.api.notification_transports import NotificationTransportSerializer
 15from authentik.events.models import (
 16    Event,
 17    Notification,
 18    NotificationSeverity,
 19    NotificationTransport,
 20    NotificationWebhookMapping,
 21    TransportMode,
 22)
 23from authentik.lib.generators import generate_id
 24from authentik.stages.email.models import get_template_choices
 25
 26
 27class TestEventTransports(TestCase):
 28    """Test Event Transports"""
 29
 30    def setUp(self) -> None:
 31        self.user = create_test_admin_user()
 32        self.event = Event.new("foo", "testing", foo="bar,").set_user(self.user)
 33        self.event.save()
 34        self.notification = Notification.objects.create(
 35            severity=NotificationSeverity.ALERT,
 36            body="foo",
 37            event=self.event,
 38            user=self.user,
 39        )
 40
 41    def test_transport_webhook(self):
 42        """Test webhook transport"""
 43        transport: NotificationTransport = NotificationTransport.objects.create(
 44            name=generate_id(),
 45            mode=TransportMode.WEBHOOK,
 46            webhook_url="http://localhost:1234/test",
 47        )
 48        with Mocker() as mocker:
 49            mocker.post("http://localhost:1234/test")
 50            transport.send(self.notification)
 51            self.assertEqual(mocker.call_count, 1)
 52            self.assertEqual(mocker.request_history[0].method, "POST")
 53            self.assertJSONEqual(
 54                mocker.request_history[0].body.decode(),
 55                {
 56                    "body": "foo",
 57                    "severity": "alert",
 58                    "user_email": self.user.email,
 59                    "user_username": self.user.username,
 60                    "event_user_email": self.user.email,
 61                    "event_user_username": self.user.username,
 62                },
 63            )
 64
 65    def test_transport_webhook_ca_invalid_unset(self):
 66        """Test webhook transport"""
 67        transport: NotificationTransport = NotificationTransport.objects.create(
 68            name=generate_id(),
 69            mode=TransportMode.WEBHOOK,
 70            webhook_url="https://localhost:1234/test",
 71        )
 72        with Mocker() as mocker:
 73            mocker.post("https://localhost:1234/test")
 74            transport.send(self.notification)
 75            self.assertEqual(mocker.call_count, 1)
 76            self.assertTrue(mocker.request_history[0].verify)
 77
 78    def test_transport_webhook_ca(self):
 79        """Test webhook transport"""
 80        kp = CertificateKeyPair.objects.create(
 81            name=generate_id(),
 82            certificate_data="foo",
 83        )
 84        transport: NotificationTransport = NotificationTransport.objects.create(
 85            name=generate_id(),
 86            mode=TransportMode.WEBHOOK,
 87            webhook_url="https://localhost:1234/test",
 88            webhook_ca=kp,
 89        )
 90        with Mocker() as mocker:
 91            mocker.post("https://localhost:1234/test")
 92            transport.send(self.notification)
 93            self.assertEqual(mocker.call_count, 1)
 94            self.assertIsNotNone(mocker.request_history[0].verify)
 95
 96    def test_transport_webhook_mapping(self):
 97        """Test webhook transport with custom mapping"""
 98        mapping_body = NotificationWebhookMapping.objects.create(
 99            name=generate_id(), expression="return request.user"
100        )
101        mapping_headers = NotificationWebhookMapping.objects.create(
102            name=generate_id(), expression="""return {"foo": "bar"}"""
103        )
104        transport: NotificationTransport = NotificationTransport.objects.create(
105            name=generate_id(),
106            mode=TransportMode.WEBHOOK,
107            webhook_url="http://localhost:1234/test",
108            webhook_mapping_body=mapping_body,
109            webhook_mapping_headers=mapping_headers,
110        )
111        with Mocker() as mocker:
112            mocker.post("http://localhost:1234/test")
113            transport.send(self.notification)
114            self.assertEqual(mocker.call_count, 1)
115            self.assertEqual(mocker.request_history[0].method, "POST")
116            self.assertEqual(mocker.request_history[0].headers["foo"], "bar")
117            self.assertJSONEqual(
118                mocker.request_history[0].body.decode(),
119                {"email": self.user.email, "pk": self.user.pk, "username": self.user.username},
120            )
121
122    def test_transport_webhook_redirect(self):
123        """Test webhook transport doesn't follow redirects"""
124        transport: NotificationTransport = NotificationTransport.objects.create(
125            name=generate_id(),
126            mode=TransportMode.WEBHOOK,
127            webhook_url="http://localhost:1234/test",
128        )
129        with Mocker() as mocker:
130            mocker.post(
131                "http://localhost:1234/test",
132                status_code=302,
133                headers={"Location": "http://localhost:1234/redirect"},
134            )
135            mocker.get("http://localhost:1234/redirect")
136            transport.send(self.notification)
137            self.assertEqual(mocker.call_count, 1)
138            self.assertEqual(mocker.request_history[0].method, "POST")
139
140    def test_transport_webhook_slack_mapping(self):
141        """Test webhook transport with custom mapping"""
142        mapping_body = NotificationWebhookMapping.objects.create(
143            name=generate_id(), expression="return request.user"
144        )
145        mapping_headers = NotificationWebhookMapping.objects.create(
146            name=generate_id(), expression="""return {"foo": "bar"}"""
147        )
148        transport: NotificationTransport = NotificationTransport.objects.create(
149            name=generate_id(),
150            mode=TransportMode.WEBHOOK_SLACK,
151            webhook_url="http://localhost:1234/test",
152            webhook_mapping_body=mapping_body,
153            webhook_mapping_headers=mapping_headers,
154        )
155        with Mocker() as mocker:
156            mocker.post("http://localhost:1234/test")
157            transport.send(self.notification)
158            self.assertEqual(mocker.call_count, 1)
159            self.assertEqual(mocker.request_history[0].method, "POST")
160            self.assertEqual(mocker.request_history[0].headers["foo"], "bar")
161            self.assertJSONEqual(
162                mocker.request_history[0].body.decode(),
163                {"email": self.user.email, "pk": self.user.pk, "username": self.user.username},
164            )
165
166    def test_transport_webhook_slack(self):
167        """Test webhook transport (slack)"""
168        transport: NotificationTransport = NotificationTransport.objects.create(
169            name=generate_id(),
170            mode=TransportMode.WEBHOOK_SLACK,
171            webhook_url="http://localhost:1234/test",
172        )
173        with Mocker() as mocker:
174            mocker.post("http://localhost:1234/test")
175            transport.send(self.notification)
176            self.assertEqual(mocker.call_count, 1)
177            self.assertEqual(mocker.request_history[0].method, "POST")
178            self.assertJSONEqual(
179                mocker.request_history[0].body.decode(),
180                {
181                    "username": "authentik",
182                    "icon_url": "https://goauthentik.io/img/icon.png",
183                    "attachments": [
184                        {
185                            "author_name": "authentik",
186                            "author_link": "https://goauthentik.io",
187                            "author_icon": "https://goauthentik.io/img/icon.png",
188                            "title": "custom_foo",
189                            "color": "#fd4b2d",
190                            "fields": [
191                                {"title": "Severity", "value": "alert", "short": True},
192                                {
193                                    "title": "Dispatched for user",
194                                    "value": self.user.username,
195                                    "short": True,
196                                },
197                                {"short": True, "title": "Event user", "value": self.user.username},
198                                {"title": "foo", "value": "bar,"},
199                            ],
200                            "footer": f"authentik {authentik_full_version()}",
201                        }
202                    ],
203                },
204            )
205
206    def test_transport_webhook_slack_redirect(self):
207        """Test webhook transport (slack) doesn't follow redirects"""
208        transport: NotificationTransport = NotificationTransport.objects.create(
209            name=generate_id(),
210            mode=TransportMode.WEBHOOK_SLACK,
211            webhook_url="http://localhost:1234/test",
212        )
213        with Mocker() as mocker:
214            mocker.post(
215                "http://localhost:1234/test",
216                status_code=302,
217                headers={"Location": "http://localhost:1234/redirect"},
218            )
219            mocker.get("http://localhost:1234/redirect")
220            transport.send(self.notification)
221            self.assertEqual(mocker.call_count, 1)
222            self.assertEqual(mocker.request_history[0].method, "POST")
223
224    def test_transport_email(self):
225        """Test email transport"""
226        transport: NotificationTransport = NotificationTransport.objects.create(
227            name=generate_id(),
228            mode=TransportMode.EMAIL,
229        )
230        with patch(
231            "authentik.stages.email.models.EmailStage.backend_class",
232            PropertyMock(return_value=EmailBackend),
233        ):
234            transport.send(self.notification)
235            self.assertEqual(len(mail.outbox), 1)
236            self.assertEqual(mail.outbox[0].subject, "authentik Notification: custom_foo")
237            self.assertIn(self.notification.body, mail.outbox[0].alternatives[0][0])
238
239    def test_transport_email_custom_template(self):
240        """Test email transport with custom template"""
241        transport: NotificationTransport = NotificationTransport.objects.create(
242            name=generate_id(),
243            mode=TransportMode.EMAIL,
244            email_template="email/event_notification.html",
245        )
246        with patch(
247            "authentik.stages.email.models.EmailStage.backend_class",
248            PropertyMock(return_value=EmailBackend),
249        ):
250            transport.send(self.notification)
251            self.assertEqual(len(mail.outbox), 1)
252            self.assertIn(self.notification.body, mail.outbox[0].alternatives[0][0])
253
254    def test_transport_email_custom_subject_prefix(self):
255        """Test email transport with custom subject prefix"""
256        transport: NotificationTransport = NotificationTransport.objects.create(
257            name=generate_id(),
258            mode=TransportMode.EMAIL,
259            email_subject_prefix="[CUSTOM] ",
260        )
261        with patch(
262            "authentik.stages.email.models.EmailStage.backend_class",
263            PropertyMock(return_value=EmailBackend),
264        ):
265            transport.send(self.notification)
266            self.assertEqual(len(mail.outbox), 1)
267            self.assertEqual(mail.outbox[0].subject, "[CUSTOM] custom_foo")
268
269    def test_transport_email_validation(self):
270        """Test email transport template validation"""
271
272        # Test valid template
273        serializer = NotificationTransportSerializer(
274            data={
275                "name": generate_id(),
276                "mode": TransportMode.EMAIL,
277                "email_template": "email/event_notification.html",
278            }
279        )
280        self.assertTrue(serializer.is_valid())
281
282        # Test invalid template - should fail due to choices validation
283        serializer = NotificationTransportSerializer(
284            data={
285                "name": generate_id(),
286                "mode": TransportMode.EMAIL,
287                "email_template": "invalid/template.html",
288            }
289        )
290        self.assertFalse(serializer.is_valid())
291        self.assertIn("email_template", serializer.errors)
292
293    def test_templates_api_endpoint(self):
294        """Test templates API endpoint returns valid templates"""
295        self.client.force_login(self.user)
296        response = self.client.get(reverse("authentik_api:emailstage-templates"))
297        self.assertEqual(response.status_code, 200)
298
299        data = response.json()
300        self.assertIsInstance(data, list)
301
302        # Check that we have at least the default templates
303        template_names = [item["name"] for item in data]
304        self.assertIn("email/event_notification.html", template_names)
305
306        # Verify all templates are valid choices
307        valid_choices = dict(get_template_choices())
308        for template in data:
309            self.assertIn(template["name"], valid_choices)
310            self.assertEqual(template["description"], valid_choices[template["name"]])
class TestEventTransports(django.test.testcases.TestCase):
 28class TestEventTransports(TestCase):
 29    """Test Event Transports"""
 30
 31    def setUp(self) -> None:
 32        self.user = create_test_admin_user()
 33        self.event = Event.new("foo", "testing", foo="bar,").set_user(self.user)
 34        self.event.save()
 35        self.notification = Notification.objects.create(
 36            severity=NotificationSeverity.ALERT,
 37            body="foo",
 38            event=self.event,
 39            user=self.user,
 40        )
 41
 42    def test_transport_webhook(self):
 43        """Test webhook transport"""
 44        transport: NotificationTransport = NotificationTransport.objects.create(
 45            name=generate_id(),
 46            mode=TransportMode.WEBHOOK,
 47            webhook_url="http://localhost:1234/test",
 48        )
 49        with Mocker() as mocker:
 50            mocker.post("http://localhost:1234/test")
 51            transport.send(self.notification)
 52            self.assertEqual(mocker.call_count, 1)
 53            self.assertEqual(mocker.request_history[0].method, "POST")
 54            self.assertJSONEqual(
 55                mocker.request_history[0].body.decode(),
 56                {
 57                    "body": "foo",
 58                    "severity": "alert",
 59                    "user_email": self.user.email,
 60                    "user_username": self.user.username,
 61                    "event_user_email": self.user.email,
 62                    "event_user_username": self.user.username,
 63                },
 64            )
 65
 66    def test_transport_webhook_ca_invalid_unset(self):
 67        """Test webhook transport"""
 68        transport: NotificationTransport = NotificationTransport.objects.create(
 69            name=generate_id(),
 70            mode=TransportMode.WEBHOOK,
 71            webhook_url="https://localhost:1234/test",
 72        )
 73        with Mocker() as mocker:
 74            mocker.post("https://localhost:1234/test")
 75            transport.send(self.notification)
 76            self.assertEqual(mocker.call_count, 1)
 77            self.assertTrue(mocker.request_history[0].verify)
 78
 79    def test_transport_webhook_ca(self):
 80        """Test webhook transport"""
 81        kp = CertificateKeyPair.objects.create(
 82            name=generate_id(),
 83            certificate_data="foo",
 84        )
 85        transport: NotificationTransport = NotificationTransport.objects.create(
 86            name=generate_id(),
 87            mode=TransportMode.WEBHOOK,
 88            webhook_url="https://localhost:1234/test",
 89            webhook_ca=kp,
 90        )
 91        with Mocker() as mocker:
 92            mocker.post("https://localhost:1234/test")
 93            transport.send(self.notification)
 94            self.assertEqual(mocker.call_count, 1)
 95            self.assertIsNotNone(mocker.request_history[0].verify)
 96
 97    def test_transport_webhook_mapping(self):
 98        """Test webhook transport with custom mapping"""
 99        mapping_body = NotificationWebhookMapping.objects.create(
100            name=generate_id(), expression="return request.user"
101        )
102        mapping_headers = NotificationWebhookMapping.objects.create(
103            name=generate_id(), expression="""return {"foo": "bar"}"""
104        )
105        transport: NotificationTransport = NotificationTransport.objects.create(
106            name=generate_id(),
107            mode=TransportMode.WEBHOOK,
108            webhook_url="http://localhost:1234/test",
109            webhook_mapping_body=mapping_body,
110            webhook_mapping_headers=mapping_headers,
111        )
112        with Mocker() as mocker:
113            mocker.post("http://localhost:1234/test")
114            transport.send(self.notification)
115            self.assertEqual(mocker.call_count, 1)
116            self.assertEqual(mocker.request_history[0].method, "POST")
117            self.assertEqual(mocker.request_history[0].headers["foo"], "bar")
118            self.assertJSONEqual(
119                mocker.request_history[0].body.decode(),
120                {"email": self.user.email, "pk": self.user.pk, "username": self.user.username},
121            )
122
123    def test_transport_webhook_redirect(self):
124        """Test webhook transport doesn't follow redirects"""
125        transport: NotificationTransport = NotificationTransport.objects.create(
126            name=generate_id(),
127            mode=TransportMode.WEBHOOK,
128            webhook_url="http://localhost:1234/test",
129        )
130        with Mocker() as mocker:
131            mocker.post(
132                "http://localhost:1234/test",
133                status_code=302,
134                headers={"Location": "http://localhost:1234/redirect"},
135            )
136            mocker.get("http://localhost:1234/redirect")
137            transport.send(self.notification)
138            self.assertEqual(mocker.call_count, 1)
139            self.assertEqual(mocker.request_history[0].method, "POST")
140
141    def test_transport_webhook_slack_mapping(self):
142        """Test webhook transport with custom mapping"""
143        mapping_body = NotificationWebhookMapping.objects.create(
144            name=generate_id(), expression="return request.user"
145        )
146        mapping_headers = NotificationWebhookMapping.objects.create(
147            name=generate_id(), expression="""return {"foo": "bar"}"""
148        )
149        transport: NotificationTransport = NotificationTransport.objects.create(
150            name=generate_id(),
151            mode=TransportMode.WEBHOOK_SLACK,
152            webhook_url="http://localhost:1234/test",
153            webhook_mapping_body=mapping_body,
154            webhook_mapping_headers=mapping_headers,
155        )
156        with Mocker() as mocker:
157            mocker.post("http://localhost:1234/test")
158            transport.send(self.notification)
159            self.assertEqual(mocker.call_count, 1)
160            self.assertEqual(mocker.request_history[0].method, "POST")
161            self.assertEqual(mocker.request_history[0].headers["foo"], "bar")
162            self.assertJSONEqual(
163                mocker.request_history[0].body.decode(),
164                {"email": self.user.email, "pk": self.user.pk, "username": self.user.username},
165            )
166
167    def test_transport_webhook_slack(self):
168        """Test webhook transport (slack)"""
169        transport: NotificationTransport = NotificationTransport.objects.create(
170            name=generate_id(),
171            mode=TransportMode.WEBHOOK_SLACK,
172            webhook_url="http://localhost:1234/test",
173        )
174        with Mocker() as mocker:
175            mocker.post("http://localhost:1234/test")
176            transport.send(self.notification)
177            self.assertEqual(mocker.call_count, 1)
178            self.assertEqual(mocker.request_history[0].method, "POST")
179            self.assertJSONEqual(
180                mocker.request_history[0].body.decode(),
181                {
182                    "username": "authentik",
183                    "icon_url": "https://goauthentik.io/img/icon.png",
184                    "attachments": [
185                        {
186                            "author_name": "authentik",
187                            "author_link": "https://goauthentik.io",
188                            "author_icon": "https://goauthentik.io/img/icon.png",
189                            "title": "custom_foo",
190                            "color": "#fd4b2d",
191                            "fields": [
192                                {"title": "Severity", "value": "alert", "short": True},
193                                {
194                                    "title": "Dispatched for user",
195                                    "value": self.user.username,
196                                    "short": True,
197                                },
198                                {"short": True, "title": "Event user", "value": self.user.username},
199                                {"title": "foo", "value": "bar,"},
200                            ],
201                            "footer": f"authentik {authentik_full_version()}",
202                        }
203                    ],
204                },
205            )
206
207    def test_transport_webhook_slack_redirect(self):
208        """Test webhook transport (slack) doesn't follow redirects"""
209        transport: NotificationTransport = NotificationTransport.objects.create(
210            name=generate_id(),
211            mode=TransportMode.WEBHOOK_SLACK,
212            webhook_url="http://localhost:1234/test",
213        )
214        with Mocker() as mocker:
215            mocker.post(
216                "http://localhost:1234/test",
217                status_code=302,
218                headers={"Location": "http://localhost:1234/redirect"},
219            )
220            mocker.get("http://localhost:1234/redirect")
221            transport.send(self.notification)
222            self.assertEqual(mocker.call_count, 1)
223            self.assertEqual(mocker.request_history[0].method, "POST")
224
225    def test_transport_email(self):
226        """Test email transport"""
227        transport: NotificationTransport = NotificationTransport.objects.create(
228            name=generate_id(),
229            mode=TransportMode.EMAIL,
230        )
231        with patch(
232            "authentik.stages.email.models.EmailStage.backend_class",
233            PropertyMock(return_value=EmailBackend),
234        ):
235            transport.send(self.notification)
236            self.assertEqual(len(mail.outbox), 1)
237            self.assertEqual(mail.outbox[0].subject, "authentik Notification: custom_foo")
238            self.assertIn(self.notification.body, mail.outbox[0].alternatives[0][0])
239
240    def test_transport_email_custom_template(self):
241        """Test email transport with custom template"""
242        transport: NotificationTransport = NotificationTransport.objects.create(
243            name=generate_id(),
244            mode=TransportMode.EMAIL,
245            email_template="email/event_notification.html",
246        )
247        with patch(
248            "authentik.stages.email.models.EmailStage.backend_class",
249            PropertyMock(return_value=EmailBackend),
250        ):
251            transport.send(self.notification)
252            self.assertEqual(len(mail.outbox), 1)
253            self.assertIn(self.notification.body, mail.outbox[0].alternatives[0][0])
254
255    def test_transport_email_custom_subject_prefix(self):
256        """Test email transport with custom subject prefix"""
257        transport: NotificationTransport = NotificationTransport.objects.create(
258            name=generate_id(),
259            mode=TransportMode.EMAIL,
260            email_subject_prefix="[CUSTOM] ",
261        )
262        with patch(
263            "authentik.stages.email.models.EmailStage.backend_class",
264            PropertyMock(return_value=EmailBackend),
265        ):
266            transport.send(self.notification)
267            self.assertEqual(len(mail.outbox), 1)
268            self.assertEqual(mail.outbox[0].subject, "[CUSTOM] custom_foo")
269
270    def test_transport_email_validation(self):
271        """Test email transport template validation"""
272
273        # Test valid template
274        serializer = NotificationTransportSerializer(
275            data={
276                "name": generate_id(),
277                "mode": TransportMode.EMAIL,
278                "email_template": "email/event_notification.html",
279            }
280        )
281        self.assertTrue(serializer.is_valid())
282
283        # Test invalid template - should fail due to choices validation
284        serializer = NotificationTransportSerializer(
285            data={
286                "name": generate_id(),
287                "mode": TransportMode.EMAIL,
288                "email_template": "invalid/template.html",
289            }
290        )
291        self.assertFalse(serializer.is_valid())
292        self.assertIn("email_template", serializer.errors)
293
294    def test_templates_api_endpoint(self):
295        """Test templates API endpoint returns valid templates"""
296        self.client.force_login(self.user)
297        response = self.client.get(reverse("authentik_api:emailstage-templates"))
298        self.assertEqual(response.status_code, 200)
299
300        data = response.json()
301        self.assertIsInstance(data, list)
302
303        # Check that we have at least the default templates
304        template_names = [item["name"] for item in data]
305        self.assertIn("email/event_notification.html", template_names)
306
307        # Verify all templates are valid choices
308        valid_choices = dict(get_template_choices())
309        for template in data:
310            self.assertIn(template["name"], valid_choices)
311            self.assertEqual(template["description"], valid_choices[template["name"]])

Test Event Transports

def setUp(self) -> None:
31    def setUp(self) -> None:
32        self.user = create_test_admin_user()
33        self.event = Event.new("foo", "testing", foo="bar,").set_user(self.user)
34        self.event.save()
35        self.notification = Notification.objects.create(
36            severity=NotificationSeverity.ALERT,
37            body="foo",
38            event=self.event,
39            user=self.user,
40        )

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

def test_transport_webhook(self):
42    def test_transport_webhook(self):
43        """Test webhook transport"""
44        transport: NotificationTransport = NotificationTransport.objects.create(
45            name=generate_id(),
46            mode=TransportMode.WEBHOOK,
47            webhook_url="http://localhost:1234/test",
48        )
49        with Mocker() as mocker:
50            mocker.post("http://localhost:1234/test")
51            transport.send(self.notification)
52            self.assertEqual(mocker.call_count, 1)
53            self.assertEqual(mocker.request_history[0].method, "POST")
54            self.assertJSONEqual(
55                mocker.request_history[0].body.decode(),
56                {
57                    "body": "foo",
58                    "severity": "alert",
59                    "user_email": self.user.email,
60                    "user_username": self.user.username,
61                    "event_user_email": self.user.email,
62                    "event_user_username": self.user.username,
63                },
64            )

Test webhook transport

def test_transport_webhook_ca_invalid_unset(self):
66    def test_transport_webhook_ca_invalid_unset(self):
67        """Test webhook transport"""
68        transport: NotificationTransport = NotificationTransport.objects.create(
69            name=generate_id(),
70            mode=TransportMode.WEBHOOK,
71            webhook_url="https://localhost:1234/test",
72        )
73        with Mocker() as mocker:
74            mocker.post("https://localhost:1234/test")
75            transport.send(self.notification)
76            self.assertEqual(mocker.call_count, 1)
77            self.assertTrue(mocker.request_history[0].verify)

Test webhook transport

def test_transport_webhook_ca(self):
79    def test_transport_webhook_ca(self):
80        """Test webhook transport"""
81        kp = CertificateKeyPair.objects.create(
82            name=generate_id(),
83            certificate_data="foo",
84        )
85        transport: NotificationTransport = NotificationTransport.objects.create(
86            name=generate_id(),
87            mode=TransportMode.WEBHOOK,
88            webhook_url="https://localhost:1234/test",
89            webhook_ca=kp,
90        )
91        with Mocker() as mocker:
92            mocker.post("https://localhost:1234/test")
93            transport.send(self.notification)
94            self.assertEqual(mocker.call_count, 1)
95            self.assertIsNotNone(mocker.request_history[0].verify)

Test webhook transport

def test_transport_webhook_mapping(self):
 97    def test_transport_webhook_mapping(self):
 98        """Test webhook transport with custom mapping"""
 99        mapping_body = NotificationWebhookMapping.objects.create(
100            name=generate_id(), expression="return request.user"
101        )
102        mapping_headers = NotificationWebhookMapping.objects.create(
103            name=generate_id(), expression="""return {"foo": "bar"}"""
104        )
105        transport: NotificationTransport = NotificationTransport.objects.create(
106            name=generate_id(),
107            mode=TransportMode.WEBHOOK,
108            webhook_url="http://localhost:1234/test",
109            webhook_mapping_body=mapping_body,
110            webhook_mapping_headers=mapping_headers,
111        )
112        with Mocker() as mocker:
113            mocker.post("http://localhost:1234/test")
114            transport.send(self.notification)
115            self.assertEqual(mocker.call_count, 1)
116            self.assertEqual(mocker.request_history[0].method, "POST")
117            self.assertEqual(mocker.request_history[0].headers["foo"], "bar")
118            self.assertJSONEqual(
119                mocker.request_history[0].body.decode(),
120                {"email": self.user.email, "pk": self.user.pk, "username": self.user.username},
121            )

Test webhook transport with custom mapping

def test_transport_webhook_redirect(self):
123    def test_transport_webhook_redirect(self):
124        """Test webhook transport doesn't follow redirects"""
125        transport: NotificationTransport = NotificationTransport.objects.create(
126            name=generate_id(),
127            mode=TransportMode.WEBHOOK,
128            webhook_url="http://localhost:1234/test",
129        )
130        with Mocker() as mocker:
131            mocker.post(
132                "http://localhost:1234/test",
133                status_code=302,
134                headers={"Location": "http://localhost:1234/redirect"},
135            )
136            mocker.get("http://localhost:1234/redirect")
137            transport.send(self.notification)
138            self.assertEqual(mocker.call_count, 1)
139            self.assertEqual(mocker.request_history[0].method, "POST")

Test webhook transport doesn't follow redirects

def test_transport_webhook_slack_mapping(self):
141    def test_transport_webhook_slack_mapping(self):
142        """Test webhook transport with custom mapping"""
143        mapping_body = NotificationWebhookMapping.objects.create(
144            name=generate_id(), expression="return request.user"
145        )
146        mapping_headers = NotificationWebhookMapping.objects.create(
147            name=generate_id(), expression="""return {"foo": "bar"}"""
148        )
149        transport: NotificationTransport = NotificationTransport.objects.create(
150            name=generate_id(),
151            mode=TransportMode.WEBHOOK_SLACK,
152            webhook_url="http://localhost:1234/test",
153            webhook_mapping_body=mapping_body,
154            webhook_mapping_headers=mapping_headers,
155        )
156        with Mocker() as mocker:
157            mocker.post("http://localhost:1234/test")
158            transport.send(self.notification)
159            self.assertEqual(mocker.call_count, 1)
160            self.assertEqual(mocker.request_history[0].method, "POST")
161            self.assertEqual(mocker.request_history[0].headers["foo"], "bar")
162            self.assertJSONEqual(
163                mocker.request_history[0].body.decode(),
164                {"email": self.user.email, "pk": self.user.pk, "username": self.user.username},
165            )

Test webhook transport with custom mapping

def test_transport_webhook_slack(self):
167    def test_transport_webhook_slack(self):
168        """Test webhook transport (slack)"""
169        transport: NotificationTransport = NotificationTransport.objects.create(
170            name=generate_id(),
171            mode=TransportMode.WEBHOOK_SLACK,
172            webhook_url="http://localhost:1234/test",
173        )
174        with Mocker() as mocker:
175            mocker.post("http://localhost:1234/test")
176            transport.send(self.notification)
177            self.assertEqual(mocker.call_count, 1)
178            self.assertEqual(mocker.request_history[0].method, "POST")
179            self.assertJSONEqual(
180                mocker.request_history[0].body.decode(),
181                {
182                    "username": "authentik",
183                    "icon_url": "https://goauthentik.io/img/icon.png",
184                    "attachments": [
185                        {
186                            "author_name": "authentik",
187                            "author_link": "https://goauthentik.io",
188                            "author_icon": "https://goauthentik.io/img/icon.png",
189                            "title": "custom_foo",
190                            "color": "#fd4b2d",
191                            "fields": [
192                                {"title": "Severity", "value": "alert", "short": True},
193                                {
194                                    "title": "Dispatched for user",
195                                    "value": self.user.username,
196                                    "short": True,
197                                },
198                                {"short": True, "title": "Event user", "value": self.user.username},
199                                {"title": "foo", "value": "bar,"},
200                            ],
201                            "footer": f"authentik {authentik_full_version()}",
202                        }
203                    ],
204                },
205            )

Test webhook transport (slack)

def test_transport_webhook_slack_redirect(self):
207    def test_transport_webhook_slack_redirect(self):
208        """Test webhook transport (slack) doesn't follow redirects"""
209        transport: NotificationTransport = NotificationTransport.objects.create(
210            name=generate_id(),
211            mode=TransportMode.WEBHOOK_SLACK,
212            webhook_url="http://localhost:1234/test",
213        )
214        with Mocker() as mocker:
215            mocker.post(
216                "http://localhost:1234/test",
217                status_code=302,
218                headers={"Location": "http://localhost:1234/redirect"},
219            )
220            mocker.get("http://localhost:1234/redirect")
221            transport.send(self.notification)
222            self.assertEqual(mocker.call_count, 1)
223            self.assertEqual(mocker.request_history[0].method, "POST")

Test webhook transport (slack) doesn't follow redirects

def test_transport_email(self):
225    def test_transport_email(self):
226        """Test email transport"""
227        transport: NotificationTransport = NotificationTransport.objects.create(
228            name=generate_id(),
229            mode=TransportMode.EMAIL,
230        )
231        with patch(
232            "authentik.stages.email.models.EmailStage.backend_class",
233            PropertyMock(return_value=EmailBackend),
234        ):
235            transport.send(self.notification)
236            self.assertEqual(len(mail.outbox), 1)
237            self.assertEqual(mail.outbox[0].subject, "authentik Notification: custom_foo")
238            self.assertIn(self.notification.body, mail.outbox[0].alternatives[0][0])

Test email transport

def test_transport_email_custom_template(self):
240    def test_transport_email_custom_template(self):
241        """Test email transport with custom template"""
242        transport: NotificationTransport = NotificationTransport.objects.create(
243            name=generate_id(),
244            mode=TransportMode.EMAIL,
245            email_template="email/event_notification.html",
246        )
247        with patch(
248            "authentik.stages.email.models.EmailStage.backend_class",
249            PropertyMock(return_value=EmailBackend),
250        ):
251            transport.send(self.notification)
252            self.assertEqual(len(mail.outbox), 1)
253            self.assertIn(self.notification.body, mail.outbox[0].alternatives[0][0])

Test email transport with custom template

def test_transport_email_custom_subject_prefix(self):
255    def test_transport_email_custom_subject_prefix(self):
256        """Test email transport with custom subject prefix"""
257        transport: NotificationTransport = NotificationTransport.objects.create(
258            name=generate_id(),
259            mode=TransportMode.EMAIL,
260            email_subject_prefix="[CUSTOM] ",
261        )
262        with patch(
263            "authentik.stages.email.models.EmailStage.backend_class",
264            PropertyMock(return_value=EmailBackend),
265        ):
266            transport.send(self.notification)
267            self.assertEqual(len(mail.outbox), 1)
268            self.assertEqual(mail.outbox[0].subject, "[CUSTOM] custom_foo")

Test email transport with custom subject prefix

def test_transport_email_validation(self):
270    def test_transport_email_validation(self):
271        """Test email transport template validation"""
272
273        # Test valid template
274        serializer = NotificationTransportSerializer(
275            data={
276                "name": generate_id(),
277                "mode": TransportMode.EMAIL,
278                "email_template": "email/event_notification.html",
279            }
280        )
281        self.assertTrue(serializer.is_valid())
282
283        # Test invalid template - should fail due to choices validation
284        serializer = NotificationTransportSerializer(
285            data={
286                "name": generate_id(),
287                "mode": TransportMode.EMAIL,
288                "email_template": "invalid/template.html",
289            }
290        )
291        self.assertFalse(serializer.is_valid())
292        self.assertIn("email_template", serializer.errors)

Test email transport template validation

def test_templates_api_endpoint(self):
294    def test_templates_api_endpoint(self):
295        """Test templates API endpoint returns valid templates"""
296        self.client.force_login(self.user)
297        response = self.client.get(reverse("authentik_api:emailstage-templates"))
298        self.assertEqual(response.status_code, 200)
299
300        data = response.json()
301        self.assertIsInstance(data, list)
302
303        # Check that we have at least the default templates
304        template_names = [item["name"] for item in data]
305        self.assertIn("email/event_notification.html", template_names)
306
307        # Verify all templates are valid choices
308        valid_choices = dict(get_template_choices())
309        for template in data:
310            self.assertIn(template["name"], valid_choices)
311            self.assertEqual(template["description"], valid_choices[template["name"]])

Test templates API endpoint returns valid templates