Skip to content
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

Improve error when redirecting with custom schemes #1002

Merged
merged 1 commit into from
May 28, 2020
Merged
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
4 changes: 4 additions & 0 deletions httpx/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,10 @@ def redirect_url(self, request: Request, response: Response) -> URL:

url = URL(location, allow_relative=True)

# Check that we can handle the scheme
if url.scheme and url.scheme not in ("http", "https"):
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In these kinds of cases, if it's a single-liner I'd often prefer not to introduce indirection. It's as clear as it can possibly be, and it's not a complicated expression.

raise InvalidURL(f'Scheme "{url.scheme}" not supported.')

# Handle malformed 'Location' headers that are "absolute" form, have no host.
# See: https://github.com/encode/httpx/issues/771
if url.scheme and not url.host:
Expand Down
20 changes: 20 additions & 0 deletions tests/client/test_redirects.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from httpx import (
URL,
AsyncClient,
InvalidURL,
NotRedirectResponse,
RequestBodyUnavailable,
TooManyRedirects,
Expand Down Expand Up @@ -140,6 +141,17 @@ async def body():
else:
return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")

elif path == b"/redirect_custom_scheme":
status_code = codes.MOVED_PERMANENTLY
headers = [(b"location", b"market://details?id=42")]
return (
b"HTTP/1.1",
status_code,
b"Moved Permanently",
headers,
ByteStream(b""),
)

return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")


Expand Down Expand Up @@ -431,3 +443,11 @@ async def test_redirect_cookie_behavior():
response = await client.get("https://example.com/")
assert response.url == "https://example.com/"
assert response.text == "Not logged in"


@pytest.mark.usefixtures("async_environment")
async def test_redirect_custom_scheme():
client = AsyncClient(dispatch=MockDispatch())
with pytest.raises(InvalidURL) as e:
await client.post("https://example.org/redirect_custom_scheme")
assert str(e.value) == 'Scheme "market" not supported.'