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 to URL.with_port() input filtering #793

Merged
merged 9 commits into from
Dec 12, 2022
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/793.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added some input restrictions on with_port() function to prevent invalid boolean inputs or out of valid port inputs; handled incorrect 0 port representation.
12 changes: 12 additions & 0 deletions tests/test_url_update_netloc.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,11 @@ def test_with_port():
assert str(url.with_port(8888)) == "http://example.com:8888"


def test_with_port_with_no_port():
url = URL("http://example.com")
assert str(url.with_port(None)) == "http://example.com"


def test_with_port_ipv6():
url = URL("http://[::1]:8080/")
assert str(url.with_port(80)) == "http://[::1]:80/"
Expand All @@ -214,3 +219,10 @@ def test_with_port_for_relative_url():
def test_with_port_invalid_type():
with pytest.raises(TypeError):
URL("http://example.com").with_port("123")
with pytest.raises(TypeError):
URL("http://example.com").with_port(True)


def test_with_port_invalid_range():
with pytest.raises(ValueError):
URL("http://example.com").with_port(-1)
9 changes: 6 additions & 3 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,7 +761,7 @@ def _make_netloc(
ret = cls._encode_host(host)
else:
ret = host
if port:
if port is not None:
ret = ret + ":" + str(port)
if password is not None:
if not user:
Expand Down Expand Up @@ -869,8 +869,11 @@ def with_port(self, port):

"""
# N.B. doesn't cleanup query/fragment
if port is not None and not isinstance(port, int):
raise TypeError(f"port should be int or None, got {type(port)}")
if port is not None:
if isinstance(port, bool) or not isinstance(port, int):
raise TypeError(f"port should be int or None, got {type(port)}")
if port < 0 or port > 65535:
raise ValueError(f"port must be between 0 and 65535, got {port}")
if not self.is_absolute():
raise ValueError("port replacement is not allowed for relative URLs")
val = self._val
Expand Down