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

Fix building the URL in BaseRequest when the host contains a port or IPv6 address #9309

Merged
merged 6 commits into from
Sep 27, 2024
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
1 change: 1 addition & 0 deletions CHANGES/9309.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed assembling the :class:`~yarl.URL` for web requests when the host contains a non-default port or IPv6 address -- by :user:`bdraco`.
10 changes: 8 additions & 2 deletions aiohttp/web_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,10 @@ def host(self) -> str:
- overridden value by .clone(host=new_host) call.
- HOST HTTP header
- socket.getfqdn() value

For example, 'example.com' or 'localhost:8080'.

For historical reasons, the port number may be included.
"""
host = self._message.headers.get(hdrs.HOST)
if host is not None:
Expand All @@ -444,8 +448,10 @@ def remote(self) -> Optional[str]:

@reify
def url(self) -> URL:
url = URL.build(scheme=self.scheme, host=self.host)
return url.join(self._rel_url)
"""The full URL of the request."""
# authority is used here because it may include the port number
# and we want yarl to parse it correctly
return URL.build(scheme=self.scheme, authority=self.host).join(self._rel_url)
bdraco marked this conversation as resolved.
Show resolved Hide resolved

@reify
def path(self) -> str:
Expand Down
10 changes: 10 additions & 0 deletions tests/test_web_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,16 @@ def test_url_url() -> None:
assert URL("http://example.com/path") == req.url


def test_url_non_default_port() -> None:
req = make_mocked_request("GET", "/path", headers={"HOST": "example.com:8123"})
assert req.url == URL("http://example.com:8123/path")


def test_url_ipv6() -> None:
req = make_mocked_request("GET", "/path", headers={"HOST": "[::1]:8123"})
assert req.url == URL("http://[::1]:8123/path")


def test_clone() -> None:
req = make_mocked_request("GET", "/path")
req2 = req.clone()
Expand Down
Loading