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
5 changes: 5 additions & 0 deletions src/validators/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ def domain(
if _relies_on_idna_mapping(value):
return False

if any(label.startswith("-") or label.endswith("-") for label in value.split(".")):
# ref: RFC 5891 (4.2.3.1), a label does not start or end with a hyphen. Once
# encoded, such an IDN label hides its hyphen behind the "xn--" prefix.
return False

if value.rstrip(".").rsplit(".", 1)[-1].isdecimal():
# ref: RFC 1123 (2.1) and RFC 3696 (2), a TLD is not all-numeric. An
# all-digit IDN label like "\u0661" is, but encodes to a letter-final A-label.
Expand Down
29 changes: 29 additions & 0 deletions tests/test_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,32 @@ def test_returns_failed_validation_on_all_numeric_idn_tld_with_trailing_dot():
def test_returns_true_on_digits_outside_or_mixed_in_tld(value: str):
"""Test returns true when digits appear only in other labels or alongside letters."""
assert domain(value)


@pytest.mark.parametrize(
"value",
[
"-bücher.de",
"bücher-.de",
"www.-bücher.de",
"www.bücher-.de",
"-пример.рф",
"example.рф-",
"-例子.中国",
],
)
@pytest.mark.parametrize("consider_tld", [False, True])
def test_returns_failed_validation_on_idn_label_with_edge_hyphen(value: str, consider_tld: bool):
"""Test returns failed validation on an IDN label that starts or ends with a hyphen."""
assert isinstance(domain(value, consider_tld=consider_tld), ValidationError)
dotted = domain(value + ".", consider_tld=consider_tld, rfc_1034=True)
assert isinstance(dotted, ValidationError)


@pytest.mark.parametrize(
"value",
["bü-cher.de", "b-ü-cher.de", "xn--bcher-kva.de", "a-b.bücher.de", "при-мер.рф"],
)
def test_returns_true_on_idn_label_with_inner_hyphen(value: str):
"""Test returns true on an IDN label with a hyphen that is not at either end."""
assert domain(value)