WebSocket writer does not enforce the RFC 6455 control frame rules
Describe the bug
WebSocketWriter does not enforce the frame rules that aiohttp's own reader enforces, so a caller can put a frame on the wire that a conforming peer has to reject. Three groups of arguments are affected:
- control frames (
ping(),pong(),close()) with a payload longer than 125 bytes (RFC 6455 §5.5); - close frames carrying a status code that must not be sent: 1005, 1006, 1015, anything in the reserved 1016–2999 range, or anything above 4999 (§7.4);
- close frames whose reason is not valid UTF-8 (§5.5.1).
The writer is shared by web.WebSocketResponse and client.ClientWebSocketResponse, so either side can emit the invalid frame. The peer's aiohttp reader then fails the connection with 1002/1007 instead of it closing cleanly, and because close() marks the response closed before the frame is written, the failure surfaces as an abnormal closure (1006) rather than as an error to the caller.
To Reproduce
import asyncio
import aiohttp
from aiohttp import WSCloseCode, web
async def run_case(name, server_action):
app = web.Application()
async def handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
try:
await server_action(ws)
except Exception as exc:
print(f"{name}: server raised {type(exc).__name__}: {exc}")
else:
print(f"{name}: server wrote the frame without error")
await asyncio.sleep(0.1)
return ws
app.router.add_get("/", handler)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "127.0.0.1", 0)
await site.start()
port = site._server.sockets[0].getsockname()[1]
try:
async with aiohttp.ClientSession() as session:
async with session.ws_connect(f"http://127.0.0.1:{port}/") as client:
msg = await client.receive(timeout=2)
print(f" client got {msg.type!r} {msg.data!r}")
finally:
await runner.cleanup()
async def main():
await run_case("ping(126 bytes)", lambda ws: ws.ping(b"x" * 126))
await run_case(
"close(code=1000, reason=124 bytes)",
lambda ws: ws.close(code=WSCloseCode.OK, message=b"x" * 124),
)
await run_case(
"close(code=1006)",
lambda ws: ws.close(code=WSCloseCode.ABNORMAL_CLOSURE),
)
await run_case("close(code=2000)", lambda ws: ws.close(code=2000))
await run_case(
"close(code=1000, reason=invalid UTF-8)",
lambda ws: ws.close(code=WSCloseCode.OK, message=b"\xff\xfe"),
)
asyncio.run(main())
Expected behavior
The writer should reject these arguments with ValueError before writing anything, mirroring the checks the reader already applies, and the connection should stay usable so the caller can still close it properly.
Logs/tracebacks
Current master (unpatched):
ping(126 bytes): server wrote the frame without error
client got <WSMsgType.ERROR: 258> WebSocketError(<WSCloseCode.PROTOCOL_ERROR: 1002>, 'Control frame payload cannot be larger than 125 bytes')
close(code=1000, reason=124 bytes): server wrote the frame without error
client got <WSMsgType.ERROR: 258> WebSocketError(<WSCloseCode.PROTOCOL_ERROR: 1002>, 'Control frame payload cannot be larger than 125 bytes')
close(code=1006): server wrote the frame without error
client got <WSMsgType.ERROR: 258> WebSocketError(<WSCloseCode.PROTOCOL_ERROR: 1002>, 'Invalid close code: 1006')
close(code=2000): server wrote the frame without error
client got <WSMsgType.ERROR: 258> WebSocketError(<WSCloseCode.PROTOCOL_ERROR: 1002>, 'Invalid close code: 2000')
close(code=1000, reason=invalid UTF-8): server wrote the frame without error
client got <WSMsgType.ERROR: 258> WebSocketError(<WSCloseCode.INVALID_TEXT: 1007>, 'Invalid UTF-8 text message')
With the writer validating the arguments first, every case raises ValueError on the sending side and the client still sees a normal 1000 close.
Python Version
$ python --version
Python 3.14.0
aiohttp Version
$ python -m pip show aiohttp
Name: aiohttp
Version: 4.0.0a2.dev0
Checked out at ae3bc97bc1260272fc19589ae09a86154e0d3668, extensions disabled (AIOHTTP_NO_EXTENSIONS=1); _websocket/writer.py and _websocket/helpers.py are not compiled, so the extension build does not affect these code paths.
multidict Version
$ python -m pip show multidict
Name: multidict
Version: 7.2.1
propcache Version
$ python -m pip show propcache
Name: propcache
Version: 0.5.4
yarl Version
$ python -m pip show yarl
Name: yarl
Version: 1.25.1
OS
Windows 11, CPython 3.14.
Related component
Server, Client
Additional context
The reader already rejects these frames: ALLOWED_CLOSE_CODES, the 125-byte control-frame check and the 1-byte close payload check all live in aiohttp/_websocket/reader_py.py, so the writer and the reader disagree about what is legal on the wire.
I have a patch with tests ready and will open a PR.
I'd like to work on this.