diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 811a2527c..e28c529e0 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,6 +1,13 @@ Full release notes, with more details and upgrade information, are available at: https://channels.readthedocs.io/en/latest/releases +4.3.3 (unreleased) +------------------ + +* ``JsonWebsocketConsumer`` / ``AsyncJsonWebsocketConsumer`` close with + 1007 on malformed JSON instead of letting ``JSONDecodeError`` kill the + process. + 4.3.2 (2025-11-20) ------------------ diff --git a/channels/generic/websocket.py b/channels/generic/websocket.py index b4d99119c..02ea10563 100644 --- a/channels/generic/websocket.py +++ b/channels/generic/websocket.py @@ -1,4 +1,5 @@ import json +import logging from asgiref.sync import async_to_sync @@ -11,6 +12,8 @@ StopConsumer, ) +logger = logging.getLogger("django.channels.generic.websocket") + class WebsocketConsumer(SyncConsumer): """ @@ -127,10 +130,19 @@ class JsonWebsocketConsumer(WebsocketConsumer): """ def receive(self, text_data=None, bytes_data=None, **kwargs): - if text_data: - self.receive_json(self.decode_json(text_data), **kwargs) - else: + if not text_data: raise ValueError("No text section for incoming WebSocket frame!") + try: + content = self.decode_json(text_data) + except json.JSONDecodeError: + self.handle_invalid_json(text_data) + return + self.receive_json(content, **kwargs) + + def handle_invalid_json(self, raw_data): + """Close with 1007 so a bad frame doesn't take down the process.""" + logger.warning("Malformed JSON on WebSocket") + self.close(code=1007) def receive_json(self, content, **kwargs): """ @@ -266,10 +278,19 @@ class AsyncJsonWebsocketConsumer(AsyncWebsocketConsumer): """ async def receive(self, text_data=None, bytes_data=None, **kwargs): - if text_data: - await self.receive_json(await self.decode_json(text_data), **kwargs) - else: + if not text_data: raise ValueError("No text section for incoming WebSocket frame!") + try: + content = await self.decode_json(text_data) + except json.JSONDecodeError: + await self.handle_invalid_json(text_data) + return + await self.receive_json(content, **kwargs) + + async def handle_invalid_json(self, raw_data): + """Close with 1007 so a bad frame doesn't take down the process.""" + logger.warning("Malformed JSON on WebSocket") + await self.close(code=1007) async def receive_json(self, content, **kwargs): """ diff --git a/docs/topics/consumers.rst b/docs/topics/consumers.rst index 294a9aeda..fcd8330ef 100644 --- a/docs/topics/consumers.rst +++ b/docs/topics/consumers.rst @@ -317,6 +317,10 @@ The only API differences are: If you want to customise the JSON encoding and decoding, you can override the ``encode_json`` and ``decode_json`` classmethods. +Malformed text frames no longer crash the worker. The connection is closed +with WebSocket code 1007; override ``handle_invalid_json`` if you want to +reply with an error payload instead. + AsyncJsonWebsocketConsumer ~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/tests/test_generic_websocket.py b/tests/test_generic_websocket.py index ddfa0e6db..484af30f6 100644 --- a/tests/test_generic_websocket.py +++ b/tests/test_generic_websocket.py @@ -327,6 +327,25 @@ def receive_json(self, data=None): await communicator.wait() +@pytest.mark.django_db(transaction=True) +@pytest.mark.asyncio +async def test_json_websocket_consumer_invalid_json(): + class TestConsumer(JsonWebsocketConsumer): + def connect(self): + self.accept() + + def receive_json(self, data=None): + self.send_json({"got": data}) + + communicator = WebsocketCommunicator(TestConsumer(), "/testws/") + connected, _ = await communicator.connect() + assert connected + await communicator.send_to(text_data="{not-json") + response = await communicator.receive_output() + assert response["type"] == "websocket.close" + assert response["code"] == 1007 + + @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio async def test_async_json_websocket_consumer(): @@ -360,6 +379,25 @@ async def receive_json(self, data=None): await communicator.wait() +@pytest.mark.django_db(transaction=True) +@pytest.mark.asyncio +async def test_async_json_websocket_consumer_invalid_json(): + class TestConsumer(AsyncJsonWebsocketConsumer): + async def connect(self): + await self.accept() + + async def receive_json(self, data=None): + await self.send_json({"got": data}) + + communicator = WebsocketCommunicator(TestConsumer(), "/testws/") + connected, _ = await communicator.connect() + assert connected + await communicator.send_to(text_data="{not-json") + response = await communicator.receive_output() + assert response["type"] == "websocket.close" + assert response["code"] == 1007 + + @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio async def test_block_underscored_type_function_call():