fix: Add validation for WebSocket subprotocols

This commit is contained in:
Pankaj Kumar Bind 2025-08-13 20:19:25 +05:30
parent 032c5608f9
commit 0cb34c063b
2 changed files with 11 additions and 1 deletions

View File

@ -71,6 +71,8 @@ class WebSocketProtocol(WebSocketServerProtocol):
subprotocols = [ subprotocols = [
x.strip() for x in unquote(value.decode("ascii")).split(",") x.strip() for x in unquote(value.decode("ascii")).split(",")
] ]
if not all(isinstance(x, str) for x in subprotocols):
raise ValueError("Invalid subprotocol value")
# Make new application instance with scope # Make new application instance with scope
self.path = request.path.encode("ascii") self.path = request.path.encode("ascii")
self.application_deferred = defer.maybeDeferred( self.application_deferred = defer.maybeDeferred(

View File

@ -138,6 +138,14 @@ class TestWebsocket(DaphneTestCase):
scope, messages = test_app.get_received() scope, messages = test_app.get_received()
self.assert_valid_websocket_scope(scope, subprotocols=subprotocols) self.assert_valid_websocket_scope(scope, subprotocols=subprotocols)
self.assert_valid_websocket_connect_message(messages[0]) self.assert_valid_websocket_connect_message(messages[0])
def test_invalid_subprotocols(self):
"""
Tests that the server rejects connections with invalid subprotocols.
"""
with DaphneTestingInstance() as test_app:
test_app.add_send_messages([{"type": "websocket.accept"}])
with self.assertRaises(TypeError):
self.websocket_handshake(test_app, subprotocols=[1, 2])
def test_xff(self): def test_xff(self):
""" """