Skip to content

Commit a0a4eaf

Browse files
xiehuanyinandgator
authored andcommitted
Require complete hostname and port matches
1 parent b3d8c26 commit a0a4eaf

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

‎src/validators/hostname.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,13 @@ def _port_validator(value: str):
3434
if value.count("]:") == 1:
3535
# with ipv6
3636
host_seg, port_seg = value.rsplit(":", 1)
37-
if _port_regex().match(f":{port_seg}"):
37+
if _port_regex().fullmatch(f":{port_seg}"):
3838
return host_seg.lstrip("[").rstrip("]")
3939

4040
if value.count(":") == 1:
4141
# with ipv4 or simple hostname
4242
host_seg, port_seg = value.rsplit(":", 1)
43-
if _port_regex().match(f":{port_seg}"):
43+
if _port_regex().fullmatch(f":{port_seg}"):
4444
return host_seg
4545

4646
return None
@@ -120,7 +120,7 @@ def _matches_simple_hostname(host: str):
120120
# hostname, not only on the dotted names handled by `domain()`.
121121
if rfc_1034 and host.endswith("."):
122122
host = host[:-1]
123-
return _simple_hostname_regex().match(host)
123+
return _simple_hostname_regex().fullmatch(host)
124124

125125
if may_have_port and (host_seg := _port_validator(value)):
126126
return (

‎tests/test_hostname.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,19 @@ def test_returns_true_on_hostname_within_rfc_length_limits(value: str):
109109
def test_returns_failed_validation_on_hostname_beyond_rfc_limits(value: str):
110110
"""Test returns failed validation on hostname beyond RFC limits."""
111111
assert isinstance(hostname(value), ValidationError)
112+
113+
114+
@pytest.mark.parametrize(
115+
"value",
116+
[
117+
"ubuntu-pc\n",
118+
"ubuntu-pc:443\n",
119+
"example.com:443\n",
120+
"127.0.0.1:22\n",
121+
"[::1]:22\n",
122+
"[dead:beef:0:0:0:0000:42:1]:5731\n",
123+
],
124+
)
125+
def test_rejects_trailing_newline_in_hostnames_and_ports(value: str):
126+
"""Test rejects trailing newline in hostnames and ports."""
127+
assert isinstance(hostname(value), ValidationError)

0 commit comments

Comments
 (0)