Skip to content

Commit 549857e

Browse files
More explicit error message when redirected to a non websocket uri
1 parent fc7cafe commit 549857e

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

src/websockets/asyncio/client.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
InvalidProxyMessage,
1919
InvalidProxyStatus,
2020
InvalidStatus,
21+
InvalidURI,
2122
ProxyError,
2223
SecurityError,
2324
)
@@ -493,7 +494,10 @@ def process_redirect(self, exc: Exception) -> Exception | str:
493494

494495
old_ws_uri = parse_uri(self.uri)
495496
new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"])
496-
new_ws_uri = parse_uri(new_uri)
497+
try:
498+
new_ws_uri = parse_uri(new_uri)
499+
except InvalidURI as uri_exception:
500+
raise InvalidURI("Redirection URI is invalid", uri_exception)
497501

498502
# If connect() received a socket, it is closed and cannot be reused.
499503
if self.connection_kwargs.get("sock") is not None:

tests/asyncio/test_client.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,25 @@ def redirect(connection, request):
354354
"cannot follow redirect to ws://invalid/ with a preexisting socket",
355355
)
356356

357+
async def test_not_a_websocket_redirect(self):
358+
"""Client raises an explicit error when redirected to an absolute uri that isn't using websocket protocole."""
359+
360+
def redirect(connection, request):
361+
response = connection.respond(http.HTTPStatus.FOUND, "")
362+
response.headers["Location"] = "https://not-a-websocket.com"
363+
return response
364+
365+
async with serve(*args, process_request=redirect) as server:
366+
host, port = get_host_port(server)
367+
with self.assertRaises(InvalidURI) as raised:
368+
async with connect("ws://overridden/", host=host, port=port):
369+
self.fail("did not raise")
370+
371+
self.assertEqual(
372+
str(raised.exception),
373+
"Redirection URI is invalid isn't a valid URI: https://not-a-websocket.com isn't a valid URI: scheme isn't ws or wss"
374+
)
375+
357376
async def test_invalid_uri(self):
358377
"""Client receives an invalid URI."""
359378
with self.assertRaises(InvalidURI):

0 commit comments

Comments
 (0)