From 8220ced9f7515901cbf0976fb48ed867ff541241 Mon Sep 17 00:00:00 2001 From: "patchback[bot]" <45432694+patchback[bot]@users.noreply.github.com> Date: Fri, 27 Sep 2024 19:15:12 +0000 Subject: [PATCH] [PR #9309/e4028333 backport][3.10] Fix building the URL in BaseRequest when the host contains a port or IPv6 address (#9318) Co-authored-by: J. Nick Koston fixes #9307 --- CHANGES/9309.bugfix.rst | 1 + aiohttp/web_request.py | 10 ++++++++-- tests/test_web_request.py | 10 ++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 CHANGES/9309.bugfix.rst diff --git a/CHANGES/9309.bugfix.rst b/CHANGES/9309.bugfix.rst new file mode 100644 index 00000000000..73870da1938 --- /dev/null +++ b/CHANGES/9309.bugfix.rst @@ -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`. diff --git a/aiohttp/web_request.py b/aiohttp/web_request.py index 91fc1f42bfe..62a08ea248b 100644 --- a/aiohttp/web_request.py +++ b/aiohttp/web_request.py @@ -431,6 +431,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: @@ -454,8 +458,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) @reify def path(self) -> str: diff --git a/tests/test_web_request.py b/tests/test_web_request.py index ba12d6f54e7..9e613bb6613 100644 --- a/tests/test_web_request.py +++ b/tests/test_web_request.py @@ -526,6 +526,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()