authentik.events.tests.test_ws_client

 1from asgiref.sync import sync_to_async
 2from channels.routing import URLRouter
 3from channels.testing import WebsocketCommunicator
 4from django.test import TransactionTestCase
 5from structlog.testing import capture_logs
 6
 7from authentik.core.tests.utils import create_test_user
 8from authentik.events.models import (
 9    Event,
10    EventAction,
11    Notification,
12    NotificationTransport,
13    TransportMode,
14)
15from authentik.lib.generators import generate_id
16from authentik.root import websocket
17
18
19class TestClientWS(TransactionTestCase):
20    def setUp(self):
21        self.user = create_test_user()
22
23    async def test_unauthenticated(self):
24        communicator = WebsocketCommunicator(
25            URLRouter(websocket.websocket_urlpatterns), "/ws/client/"
26        )
27        connected, _ = await communicator.connect()
28        self.assertFalse(connected)
29
30    async def test_non_utf8_headers(self):
31        """Header values that aren't valid UTF-8 don't break the connection"""
32        communicator = WebsocketCommunicator(
33            URLRouter(websocket.websocket_urlpatterns),
34            "/ws/client/",
35            headers=[(b"user-agent", b"Mozilla/5.0 Meta\xa0AI"), (b"x-forwarded-for", b"\xff")],
36        )
37        communicator.scope["user"] = self.user
38        with capture_logs() as logs:
39            connected, _ = await communicator.connect()
40        self.assertTrue(connected)
41        log = next(log for log in logs if log.get("scheme") == "ws")
42        self.assertEqual(log["user_agent"], "Mozilla/5.0 Meta\\xa0AI")
43        self.assertEqual(log["remote"], "\\xff")
44        await communicator.disconnect()
45
46    async def test_notification(self):
47        communicator = WebsocketCommunicator(
48            URLRouter(websocket.websocket_urlpatterns), "/ws/client/"
49        )
50        communicator.scope["user"] = self.user
51        connected, _ = await communicator.connect()
52        self.assertTrue(connected)
53
54        transport = await NotificationTransport.objects.acreate(
55            name=generate_id(), mode=TransportMode.LOCAL
56        )
57        event = await sync_to_async(Event.new)(EventAction.LOGIN)
58        event.set_user(self.user)
59        await event.asave()
60        notification = Notification(
61            user=self.user,
62            body="foo",
63            event=event,
64            hyperlink="goauthentik.io",
65            hyperlink_label="a link",
66        )
67        await sync_to_async(transport.send_local)(notification)
68
69        evt = await communicator.receive_json_from(timeout=5)
70        self.assertEqual(evt["message_type"], "notification.new")
71        self.assertEqual(evt["id"], str(notification.pk))
72        self.assertEqual(evt["data"]["pk"], str(notification.pk))
73        self.assertEqual(evt["data"]["body"], "foo")
74        self.assertEqual(evt["data"]["event"]["pk"], str(event.pk))
75
76        await communicator.disconnect()
class TestClientWS(django.test.testcases.TransactionTestCase):
20class TestClientWS(TransactionTestCase):
21    def setUp(self):
22        self.user = create_test_user()
23
24    async def test_unauthenticated(self):
25        communicator = WebsocketCommunicator(
26            URLRouter(websocket.websocket_urlpatterns), "/ws/client/"
27        )
28        connected, _ = await communicator.connect()
29        self.assertFalse(connected)
30
31    async def test_non_utf8_headers(self):
32        """Header values that aren't valid UTF-8 don't break the connection"""
33        communicator = WebsocketCommunicator(
34            URLRouter(websocket.websocket_urlpatterns),
35            "/ws/client/",
36            headers=[(b"user-agent", b"Mozilla/5.0 Meta\xa0AI"), (b"x-forwarded-for", b"\xff")],
37        )
38        communicator.scope["user"] = self.user
39        with capture_logs() as logs:
40            connected, _ = await communicator.connect()
41        self.assertTrue(connected)
42        log = next(log for log in logs if log.get("scheme") == "ws")
43        self.assertEqual(log["user_agent"], "Mozilla/5.0 Meta\\xa0AI")
44        self.assertEqual(log["remote"], "\\xff")
45        await communicator.disconnect()
46
47    async def test_notification(self):
48        communicator = WebsocketCommunicator(
49            URLRouter(websocket.websocket_urlpatterns), "/ws/client/"
50        )
51        communicator.scope["user"] = self.user
52        connected, _ = await communicator.connect()
53        self.assertTrue(connected)
54
55        transport = await NotificationTransport.objects.acreate(
56            name=generate_id(), mode=TransportMode.LOCAL
57        )
58        event = await sync_to_async(Event.new)(EventAction.LOGIN)
59        event.set_user(self.user)
60        await event.asave()
61        notification = Notification(
62            user=self.user,
63            body="foo",
64            event=event,
65            hyperlink="goauthentik.io",
66            hyperlink_label="a link",
67        )
68        await sync_to_async(transport.send_local)(notification)
69
70        evt = await communicator.receive_json_from(timeout=5)
71        self.assertEqual(evt["message_type"], "notification.new")
72        self.assertEqual(evt["id"], str(notification.pk))
73        self.assertEqual(evt["data"]["pk"], str(notification.pk))
74        self.assertEqual(evt["data"]["body"], "foo")
75        self.assertEqual(evt["data"]["event"]["pk"], str(event.pk))
76
77        await communicator.disconnect()

A class whose instances are single test cases.

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

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

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

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

When subclassing TestCase, you can set these attributes:

  • failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'.
  • longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in addition to any explicit message passed.
  • maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required.
def setUp(self):
21    def setUp(self):
22        self.user = create_test_user()

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

async def test_unauthenticated(self):
24    async def test_unauthenticated(self):
25        communicator = WebsocketCommunicator(
26            URLRouter(websocket.websocket_urlpatterns), "/ws/client/"
27        )
28        connected, _ = await communicator.connect()
29        self.assertFalse(connected)
async def test_non_utf8_headers(self):
31    async def test_non_utf8_headers(self):
32        """Header values that aren't valid UTF-8 don't break the connection"""
33        communicator = WebsocketCommunicator(
34            URLRouter(websocket.websocket_urlpatterns),
35            "/ws/client/",
36            headers=[(b"user-agent", b"Mozilla/5.0 Meta\xa0AI"), (b"x-forwarded-for", b"\xff")],
37        )
38        communicator.scope["user"] = self.user
39        with capture_logs() as logs:
40            connected, _ = await communicator.connect()
41        self.assertTrue(connected)
42        log = next(log for log in logs if log.get("scheme") == "ws")
43        self.assertEqual(log["user_agent"], "Mozilla/5.0 Meta\\xa0AI")
44        self.assertEqual(log["remote"], "\\xff")
45        await communicator.disconnect()

Header values that aren't valid UTF-8 don't break the connection

async def test_notification(self):
47    async def test_notification(self):
48        communicator = WebsocketCommunicator(
49            URLRouter(websocket.websocket_urlpatterns), "/ws/client/"
50        )
51        communicator.scope["user"] = self.user
52        connected, _ = await communicator.connect()
53        self.assertTrue(connected)
54
55        transport = await NotificationTransport.objects.acreate(
56            name=generate_id(), mode=TransportMode.LOCAL
57        )
58        event = await sync_to_async(Event.new)(EventAction.LOGIN)
59        event.set_user(self.user)
60        await event.asave()
61        notification = Notification(
62            user=self.user,
63            body="foo",
64            event=event,
65            hyperlink="goauthentik.io",
66            hyperlink_label="a link",
67        )
68        await sync_to_async(transport.send_local)(notification)
69
70        evt = await communicator.receive_json_from(timeout=5)
71        self.assertEqual(evt["message_type"], "notification.new")
72        self.assertEqual(evt["id"], str(notification.pk))
73        self.assertEqual(evt["data"]["pk"], str(notification.pk))
74        self.assertEqual(evt["data"]["body"], "foo")
75        self.assertEqual(evt["data"]["event"]["pk"], str(event.pk))
76
77        await communicator.disconnect()