Skip to content

Commit ea6f807

Browse files
committed
Reject malformed port values
1 parent 978f2e6 commit ea6f807

2 files changed

Lines changed: 13 additions & 5 deletions

File tree

src/hyperlink/_url.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ def __nonzero__(self):
163163
r"|(?P<bad_host>.*?))?"
164164
r"(?::(?P<port>.*))?$"
165165
)
166+
_PORT_RE = re.compile(r"\A[0-9]+\Z")
166167

167168

168169
_HEX_CHAR_MAP = dict(
@@ -1407,12 +1408,11 @@ def from_text(cls, text):
14071408
host = au_gs["ipv6_host"] or au_gs["plain_host"]
14081409
port = au_gs["port"]
14091410
if port is not None:
1410-
try:
1411-
port = int(port) # type: ignore[assignment] # FIXME, see below
1412-
except ValueError:
1413-
if not port: # TODO: excessive?
1414-
raise URLParseError("port must not be empty: %r" % au_text)
1411+
if not port: # TODO: excessive?
1412+
raise URLParseError("port must not be empty: %r" % au_text)
1413+
if not _PORT_RE.match(port):
14151414
raise URLParseError("expected integer for port, not %r" % port)
1415+
port = int(port) # type: ignore[assignment] # FIXME, see below
14161416

14171417
scheme = gs["scheme"] or u""
14181418
fragment = gs["fragment"] or u""

src/hyperlink/test/test_url.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1114,6 +1114,14 @@ def test_invalid_ipv6(self):
11141114
def test_invalid_port(self):
11151115
# type: () -> None
11161116
self.assertRaises(URLParseError, URL.from_text, "ftp://portmouth:smash")
1117+
for url_text in [
1118+
"http://example.com: 11",
1119+
"http://example.com:+11",
1120+
"http://example.com:-11",
1121+
"http://example.com:1_1",
1122+
u"http://example.com:\u0ed1",
1123+
]:
1124+
self.assertRaises(URLParseError, URL.from_text, url_text)
11171125
self.assertRaises(
11181126
ValueError,
11191127
URL.from_text,

0 commit comments

Comments
 (0)