diff --git a/tests/test_connection.py b/tests/test_connection.py index be4445d..c3cf2b4 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -847,6 +847,22 @@ async def handler(stream: trio.SocketStream) -> None: await client.send_message('Hello from client!') +@fail_after(1) +async def test_client_ipv6_host_header(nursery: trio.Nursery) -> None: + async def handler(stream: trio.SocketStream) -> None: + request = await stream.receive_some() + assert f'\r\nhost: [::1]:{port}\r\n'.encode() in request.lower() + await stream.send_all(b'HTTP/1.1 400 Bad Request\r\n' + b'Content-Length: 0\r\n\r\n') + serve_fn = partial(trio.serve_tcp, handler, 0, host='::1') + raw_listeners = await nursery.start(serve_fn) + listeners = cast("list[trio.SocketListener]", raw_listeners) + port = listeners[0].socket.getsockname()[1] + with pytest.raises(ConnectionRejected): + async with open_websocket('::1', port, RESOURCE, use_ssl=False): + pass + + @fail_after(TIMEOUT_TEST_MAX_DURATION) async def test_client_open_timeout( nursery: trio.Nursery, diff --git a/trio_websocket/_impl.py b/trio_websocket/_impl.py index 188e2bf..b78390b 100644 --- a/trio_websocket/_impl.py +++ b/trio_websocket/_impl.py @@ -367,10 +367,12 @@ async def connect_websocket( else: stream = await trio.open_ssl_over_tcp_stream(host, port, ssl_context=ssl_context, https_compatible=True) - if port in (80, 443): - host_header = host + if ':' in host: + host_header = f'[{host}]' else: - host_header = f'{host}:{port}' + host_header = host + if port not in (80, 443): + host_header = f'{host_header}:{port}' connection = WebSocketConnection(stream, WSConnection(ConnectionType.CLIENT), host=host_header,