Skip to content

Commit

Permalink
Fix to URL.with_port() input filtering (#793)
Browse files Browse the repository at this point in the history
* Handled case where update_query() is handed None as an argument. Added corresponding test file as well.

* Added implementation and tests

* Got rid of irrelevant test case for this branch

* Cleanup

* Readjusted to include 0 for ports (unsure if needed)

* Create 793.bugfix.rst

* Update 793.bugfix.rst

Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
  • Loading branch information
dereckt and asvetlov committed Dec 12, 2022
1 parent d703adb commit 94b8679
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGES/793.bugfix.rst
@@ -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
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
Expand Up @@ -761,7 +761,7 @@ def _make_netloc(
ret = cls._encode_host(host)
else:
ret = host
if port:

This comment has been minimized.

Copy link
@commonism

commonism Jun 7, 2023

Contributor

for urls created with URL.build(…, port="") this creates scheme://host:/

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

0 comments on commit 94b8679

Please sign in to comment.