File size: 4,004 Bytes
a6be783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from unittest.mock import patch

from asgiref.sync import async_to_sync
from rest_framework_simplejwt.tokens import AccessToken

from .chat_test_support import ChatWebSocketTestCase
from ..models import ChatMessage, ChatRoom


class ChatWebSocketAuthenticationTests(ChatWebSocketTestCase):
    def test_anonymous_socket_is_rejected(self):
        async def run():
            communicator = self._communicator()
            connected, _ = await communicator.connect()
            self.assertTrue(connected)
            close_event = await communicator.receive_output(timeout=2)
            self.assertEqual(close_event["type"], "websocket.close")
            self.assertEqual(close_event["code"], 4401)
        async_to_sync(run)()

    def test_invalid_token_is_rejected(self):
        async def run():
            communicator = self._communicator("not-a-valid-token")
            connected, _ = await communicator.connect()
            self.assertTrue(connected)
            close_event = await communicator.receive_output(timeout=2)
            self.assertEqual(close_event["code"], 4401)
        async_to_sync(run)()

    def test_non_participant_cannot_join_private_room(self):
        token = str(AccessToken.for_user(self.other))
        async def run():
            communicator = self._communicator(token)
            connected, _ = await communicator.connect()
            self.assertTrue(connected)
            close_event = await communicator.receive_output(timeout=2)
            self.assertEqual(close_event["code"], 4403)
        async_to_sync(run)()

    def test_authenticated_member_can_join_and_identity_cannot_be_spoofed(self):
        token = str(AccessToken.for_user(self.member))
        async def run():
            communicator = self._communicator(token)
            connected, protocol = await communicator.connect()
            self.assertTrue(connected)
            self.assertEqual(protocol, "jwt")  # token itself is never negotiated/echoed
            await communicator.receive_json_from(timeout=2)  # presence event
            await communicator.send_json_to({
                "type": "message", "message": "Authenticated message",
                "user_id": self.other.pk, "username": self.other.username,
            })
            payload = await communicator.receive_json_from(timeout=2)
            await communicator.disconnect()
            return payload
        with patch("api.consumers_events.publish_chat_to_nats"):
            payload = async_to_sync(run)()
        self.assertEqual(payload["user_id"], self.member.pk)
        self.assertEqual(payload["username"], self.member.username)
        self.assertEqual(ChatMessage.objects.get().sender_id, self.member.pk)

    def test_socket_answers_heartbeat_without_persisting_chat_message(self):
        token = str(AccessToken.for_user(self.member))
        async def run():
            communicator = self._communicator(token)
            connected, _ = await communicator.connect()
            self.assertTrue(connected)
            await communicator.receive_json_from(timeout=2)  # presence event
            await communicator.send_json_to({"type": "ping"})
            response = await communicator.receive_json_from(timeout=2)
            await communicator.disconnect()
            return response
        response = async_to_sync(run)()
        self.assertEqual(response, {"type": "pong"})
        self.assertFalse(ChatMessage.objects.exists())

    def test_missing_room_is_not_created(self):
        token = str(AccessToken.for_user(self.member))
        async def run():
            communicator = self._communicator(token, "room-that-does-not-exist")
            connected, _ = await communicator.connect()
            self.assertTrue(connected)
            close_event = await communicator.receive_output(timeout=2)
            self.assertEqual(close_event["code"], 4404)
        async_to_sync(run)()
        self.assertFalse(ChatRoom.objects.filter(name="room-that-does-not-exist").exists())