diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py index d1c83c151ce..6a0f22d73c6 100644 --- a/aiohttp/client_reqrep.py +++ b/aiohttp/client_reqrep.py @@ -403,9 +403,8 @@ def update_host(self, url: URL) -> None: raise InvalidURL(url) # basic auth info - username, password = url.user, url.password - if username or password: - self.auth = helpers.BasicAuth(username or "", password or "") + if url.raw_user or url.raw_password: + self.auth = helpers.BasicAuth(url.user or "", url.password or "") def update_version(self, version: Union[http.HttpVersion, str]) -> None: """Convert request version to two elements tuple. diff --git a/aiohttp/helpers.py b/aiohttp/helpers.py index 097f711a1da..13a531d5cab 100644 --- a/aiohttp/helpers.py +++ b/aiohttp/helpers.py @@ -163,7 +163,9 @@ def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth" """Create BasicAuth from url.""" if not isinstance(url, URL): raise TypeError("url should be yarl.URL instance") - if url.user is None and url.password is None: + # Check raw_user and raw_password first as yarl is likely + # to already have these values parsed from the netloc in the cache. + if url.raw_user is None and url.raw_password is None: return None return cls(url.user or "", url.password or "", encoding=encoding) @@ -174,11 +176,12 @@ def encode(self) -> str: def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: - auth = BasicAuth.from_url(url) - if auth is None: + """Remove user and password from URL if present and return BasicAuth object.""" + # Check raw_user and raw_password first as yarl is likely + # to already have these values parsed from the netloc in the cache. + if url.raw_user is None and url.raw_password is None: return url, None - else: - return url.with_user(None), auth + return url.with_user(None), BasicAuth(url.user or "", url.password or "") def netrc_from_env() -> Optional[netrc.netrc]: diff --git a/tests/test_helpers.py b/tests/test_helpers.py index a9e31d13249..6f45ceca0b9 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -197,6 +197,12 @@ def test_basic_auth_no_user_from_url() -> None: assert auth.password == "pass" +def test_basic_auth_no_auth_from_url() -> None: + url = URL("http://example.com") + auth = helpers.BasicAuth.from_url(url) + assert auth is None + + def test_basic_auth_from_not_url() -> None: with pytest.raises(TypeError): helpers.BasicAuth.from_url("http://user:pass@example.com")