Skip to content
Open
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
6 changes: 3 additions & 3 deletions src/validators/hostname.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ def _port_regex():
@lru_cache
def _simple_hostname_regex():
"""Simple hostname validation regex."""
# {0,59} because two characters are already matched at
# the beginning and at the end, making the range {1, 61}
# RFC 1035 limits each label to 63 octets. The first and last
# characters leave room for up to 61 characters in between.
return re.compile(
r"^(?!-)[a-z0-9](?:[a-z0-9-]{0,59}[a-z0-9])?(?<!-)$", re.IGNORECASE | re.ASCII
r"^(?!-)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?<!-)$", re.IGNORECASE | re.ASCII
)


Expand Down
13 changes: 13 additions & 0 deletions tests/test_hostname.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,16 @@ def test_returns_true_on_valid_top_level_domain_hostname(value: str):
def test_returns_failed_validation_on_invalid_top_level_domain_hostname(value: str):
"""Test returns failed validation on hostname with a TLD not allowed by IANA."""
assert isinstance(hostname(value, consider_tld=True), ValidationError)


@pytest.mark.parametrize("length", [1, 61, 62, 63, 64])
@pytest.mark.parametrize("port", ["", ":8080"])
@pytest.mark.parametrize("rfc_1034", [False, True])
def test_simple_hostname_label_length(length: int, port: str, rfc_1034: bool):
"""Allow single labels up to 63 characters, with optional dots and ports."""
value = "a" * length + ("." if rfc_1034 else "") + port
result = hostname(value, rfc_1034=rfc_1034)
if length <= 63:
assert result is True
else:
assert isinstance(result, ValidationError)
11 changes: 11 additions & 0 deletions tests/test_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,3 +299,14 @@ def test_returns_true_on_valid_top_level_domain_url(value: str):
def test_returns_failed_validation_on_invalid_top_level_domain_url(value: str):
"""Test returns failed validation on url with a TLD not allowed by IANA."""
assert isinstance(url(value, consider_tld=True), ValidationError)


@pytest.mark.parametrize("length", [61, 62, 63, 64])
@pytest.mark.parametrize("port", ["", ":8080"])
def test_url_simple_hostname_label_length(length: int, port: str):
"""Apply the 63-character label limit to URLs allowing simple hosts."""
result = url("http://" + "a" * length + port + "/", simple_host=True)
if length <= 63:
assert result is True
else:
assert isinstance(result, ValidationError)