Skip to content

More explicit error message when redirected to a non websocket uri #1632

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
6 changes: 5 additions & 1 deletion src/websockets/asyncio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
InvalidProxyMessage,
InvalidProxyStatus,
InvalidStatus,
InvalidURI,
ProxyError,
SecurityError,
)
Expand Down Expand Up @@ -493,7 +494,10 @@ def process_redirect(self, exc: Exception) -> Exception | str:

old_ws_uri = parse_uri(self.uri)
new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"])
new_ws_uri = parse_uri(new_uri)
try:
new_ws_uri = parse_uri(new_uri)
except InvalidURI as uri_exception:
raise InvalidURI("Redirection URI is invalid", uri_exception)

# If connect() received a socket, it is closed and cannot be reused.
if self.connection_kwargs.get("sock") is not None:
Expand Down
19 changes: 19 additions & 0 deletions tests/asyncio/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,25 @@ def redirect(connection, request):
"cannot follow redirect to ws://invalid/ with a preexisting socket",
)

async def test_not_a_websocket_redirect(self):
"""Client raises an explicit error when redirected to an absolute uri that isn't using websocket protocole."""

def redirect(connection, request):
response = connection.respond(http.HTTPStatus.FOUND, "")
response.headers["Location"] = "https://not-a-websocket.com"
return response

async with serve(*args, process_request=redirect) as server:
host, port = get_host_port(server)
with self.assertRaises(InvalidURI) as raised:
async with connect("ws://overridden/", host=host, port=port):
self.fail("did not raise")

self.assertEqual(
str(raised.exception),
"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",
)

async def test_invalid_uri(self):
"""Client receives an invalid URI."""
with self.assertRaises(InvalidURI):
Expand Down