Skip to content

Commit 94a22b8

Browse files
Fix url parsing of ipv6 urls on URL.replace (#1965)
Co-authored-by: Florimond Manca <florimond.manca@protonmail.com>
1 parent 51c1de1 commit 94a22b8

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

starlette/datastructures.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,11 +113,18 @@ def replace(self, **kwargs: typing.Any) -> "URL":
113113
or "hostname" in kwargs
114114
or "port" in kwargs
115115
):
116-
hostname = kwargs.pop("hostname", self.hostname)
116+
hostname = kwargs.pop("hostname", None)
117117
port = kwargs.pop("port", self.port)
118118
username = kwargs.pop("username", self.username)
119119
password = kwargs.pop("password", self.password)
120120

121+
if hostname is None:
122+
netloc = self.netloc
123+
_, _, hostname = netloc.rpartition("@")
124+
125+
if hostname[-1] != "]":
126+
hostname = hostname.rsplit(":", 1)[0]
127+
121128
netloc = hostname
122129
if port is not None:
123130
netloc += f":{port}"

tests/test_datastructures.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,24 @@ def test_url():
4040
assert new == "https://example.com:123/path/to/somewhere?abc=123#anchor"
4141
assert new.hostname == "example.com"
4242

43+
ipv6_url = URL("https://[fe::2]:12345")
44+
new = ipv6_url.replace(port=8080)
45+
assert new == "https://[fe::2]:8080"
46+
47+
new = ipv6_url.replace(username="username", password="password")
48+
assert new == "https://username:password@[fe::2]:12345"
49+
assert new.netloc == "username:password@[fe::2]:12345"
50+
51+
ipv6_url = URL("https://[fe::2]")
52+
new = ipv6_url.replace(port=123)
53+
assert new == "https://[fe::2]:123"
54+
55+
url = URL("http://u:p@host/")
56+
assert url.replace(hostname="bar") == URL("http://u:p@bar/")
57+
58+
url = URL("http://u:p@host:80")
59+
assert url.replace(port=88) == URL("http://u:p@host:88")
60+
4361

4462
def test_url_query_params():
4563
u = URL("https://example.org/path/?page=3")

0 commit comments

Comments
 (0)