Skip to content
Open
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
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Release History

- Require ``event_hint`` when constructing ``RemoteProtocolError``.
This is an API-breaking change.
- Combine tokens from repeated ``Connection`` header fields when validating
client and server handshakes.

1.3.2 (2025-11-20)
------------------
Expand Down
12 changes: 6 additions & 6 deletions src/wsproto/handshake.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def _process_connection_request(
raise RemoteProtocolError(
msg, event_hint=RejectConnection(),
)
connection_tokens = None
connection_tokens: list[str] = []
extensions: list[str] = []
host = None
key = None
Expand All @@ -208,7 +208,7 @@ def _process_connection_request(
for name, value in event.headers:
name = name.lower()
if name == b"connection":
connection_tokens = split_comma_header(value)
connection_tokens.extend(split_comma_header(value))
elif name == b"host":
host = value.decode("idna")
continue # Skip appending to headers
Expand All @@ -225,7 +225,7 @@ def _process_connection_request(
elif name == b"upgrade":
upgrade = value
headers.append((name, value))
if connection_tokens is None or not any(
if not any(
token.lower() == "upgrade" for token in connection_tokens
):
msg = "Missing header, 'Connection: Upgrade'"
Expand Down Expand Up @@ -393,15 +393,15 @@ def _establish_client_connection(
assert self._nonce is not None

accept = None
connection_tokens = None
connection_tokens: list[str] = []
accepts: list[str] = []
subprotocol = None
upgrade = b""
headers: Headers = []
for name, value in event.headers:
name = name.lower()
if name == b"connection":
connection_tokens = split_comma_header(value)
connection_tokens.extend(split_comma_header(value))
continue # Skip appending to headers
if name == b"sec-websocket-extensions":
accepts = split_comma_header(value)
Expand All @@ -417,7 +417,7 @@ def _establish_client_connection(
continue # Skip appending to headers
headers.append((name, value))

if connection_tokens is None or not any(
if not any(
token.lower() == "upgrade" for token in connection_tokens
):
msg = "Missing header, 'Connection: Upgrade'"
Expand Down
66 changes: 66 additions & 0 deletions tests/test_connection_header_fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""Combine Connection tokens from every field line during the handshake."""

from __future__ import annotations

import pytest

from wsproto import ConnectionType, WSConnection
from wsproto.connection import ConnectionState
from wsproto.events import AcceptConnection, BytesMessage, Request
from wsproto.utilities import RemoteProtocolError


@pytest.mark.parametrize("server_side", [False, True])
@pytest.mark.parametrize("chunk_size", [1, 65536])
@pytest.mark.parametrize(
("values", "accepted"),
[
([b"Upgrade", b"keep-alive"], True),
([b"keep-alive", b"Upgrade"], True),
([b"keep-alive", b"uPgRaDe", b"custom-hop"], True),
([b"keep-alive, uPgRaDe"], True),
([b"keep-alive", b"close"], False),
([], False),
],
)
def test_connection_field_lines(
server_side: bool,
chunk_size: int,
values: list[bytes],
accepted: bool,
) -> None:
client = WSConnection(ConnectionType.CLIENT)
server = WSConnection(ConnectionType.SERVER)
wire = client.send(Request(host="localhost", target="/"))
receiver = server
if not server_side:
server.receive_data(wire)
assert isinstance(next(server.events()), Request)
wire = server.send(AcceptConnection())
receiver = client

replacement = b"".join((b"Connection" if index % 2 == 0 else b"cOnNeCtIoN") + b": " + value + b"\r\n" for index, value in enumerate(values))
assert b"Connection: Upgrade\r\n" in wire
wire = wire.replace(b"Connection: Upgrade\r\n", replacement)

def receive() -> None:
for offset in range(0, len(wire), chunk_size):
receiver.receive_data(wire[offset : offset + chunk_size])

if not accepted:
with pytest.raises(RemoteProtocolError, match="Missing header, 'Connection: Upgrade'"):
receive()
return

receive()
event = next(receiver.events())
assert isinstance(event, Request if server_side else AcceptConnection)
if server_side:
client.receive_data(server.send(AcceptConnection()))
assert isinstance(next(client.events()), AcceptConnection)
assert client.state is ConnectionState.OPEN
assert server.state is ConnectionState.OPEN

payload = b"\x00\x01\x00\xff" * 40
server.receive_data(client.send(BytesMessage(data=payload)))
assert b"".join(event.data for event in server.events() if isinstance(event, BytesMessage)) == payload