Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.txt
Original file line number Diff line number Diff line change
@@ -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)
------------------

Expand Down
33 changes: 27 additions & 6 deletions channels/generic/websocket.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import logging

from asgiref.sync import async_to_sync

Expand All @@ -11,6 +12,8 @@
StopConsumer,
)

logger = logging.getLogger("django.channels.generic.websocket")


class WebsocketConsumer(SyncConsumer):
"""
Expand Down Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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):
"""
Expand Down
4 changes: 4 additions & 0 deletions docs/topics/consumers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
38 changes: 38 additions & 0 deletions tests/test_generic_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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():
Expand Down