Skip to content

Commit dbd2cbc

Browse files
committed
Validate mixed IDN hosts label by label
1 parent 3fba971 commit dbd2cbc

3 files changed

Lines changed: 56 additions & 17 deletions

File tree

‎Documentation/connection-strings.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,11 @@ chronicle://[<client-id>:<client-secret>@]<host>[:<port>][/][?skipTlsValidation=
3030
preserved. Rejecting unassigned characters also rejects newly assigned format characters on older Python versions.
3131
- Internationalised host names are accepted as Unicode (`münchen.example`, `例え.テスト`) or ASCII punycode
3232
(`xn--mnchen-3ya.example`, `xn--r8jz45g.xn--zckzah`). The supplied representation is preserved, as in the .NET client.
33-
Unicode host names must round-trip through IDNA unchanged after NFC normalisation and lowercasing; uppercase forms
34-
are accepted. Nameprep mappings that change other characters are rejected, including fullwidth letters or digits,
35-
invisible joiners, mapped dot characters and `ß` mapped to `ss`.
33+
Unicode and punycode labels may be mixed, for example `münchen.xn--mnchen-3ya`. Each label containing non-ASCII
34+
characters must round-trip through IDNA unchanged after NFC normalisation and lowercasing; uppercase forms are
35+
accepted. ASCII punycode labels in mixed hosts are decoded for validation without requiring a Unicode spelling.
36+
Nameprep mappings that change other characters are rejected, including fullwidth letters or digits, invisible
37+
joiners, mapped dot characters and `ß` mapped to `ss`.
3638
Host names are validated using their IDNA-encoded ASCII form: non-empty labels of 1–63 characters, starting and
3739
ending with a letter or digit, and at most 253 characters in total, ignoring an optional trailing dot, which is
3840
preserved.

‎src/cratis_chronicle/connection_string.py‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -259,18 +259,21 @@ def _parse_host_and_port(host_and_port: str) -> tuple[str, int]:
259259

260260
def _encode_idn_host(host: str) -> str:
261261
"""Validate Unicode DNS names through IDNA without changing the returned host representation."""
262-
ascii_host: str | None
263-
try:
264-
ascii_host = host.lower().encode("idna").decode("ascii")
265-
round_trip_host = ascii_host.encode("ascii").decode("idna")
266-
if round_trip_host != unicodedata.normalize("NFC", host).lower():
267-
ascii_host = None
268-
except UnicodeError:
269-
ascii_host = None
270-
if ascii_host is None:
271-
# The codec exception can contain the input host; do not retain it in cause or context.
272-
raise InvalidHostError("The host is not a valid internationalised host name")
273-
return ascii_host
262+
ascii_labels = []
263+
for label in host.split("."):
264+
ascii_label: str | None
265+
try:
266+
ascii_label = label.lower().encode("idna").decode("ascii")
267+
round_trip_label = ascii_label.encode("ascii").decode("idna")
268+
if not label.isascii() and round_trip_label != unicodedata.normalize("NFC", label).lower():
269+
ascii_label = None
270+
except UnicodeError:
271+
ascii_label = None
272+
if ascii_label is None:
273+
# The codec exception can contain the input label; do not retain it in cause or context.
274+
raise InvalidHostError("The host is not a valid internationalised host name")
275+
ascii_labels.append(ascii_label)
276+
return ".".join(ascii_labels)
274277

275278

276279
def _parse_port(port_text: str | None) -> int:

‎tests/test_connection_string.py‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -696,7 +696,9 @@ def test_accepts_idn_hosts_and_preserves_the_supplied_representation(
696696
assert str(options) == f"chronicle://id:****@{host}:35000"
697697

698698

699-
@pytest.mark.parametrize("host", ["PRIVATE_HOST\ud800.example", "é" * 58 + ".example", "münchen.xn--"])
699+
@pytest.mark.parametrize(
700+
"host", ["PRIVATE_HOST\ud800.example", "é" * 58 + ".example", "münchen.xn--", "münchen.XN--.example"]
701+
)
700702
def test_idna_conversion_failures_raise_a_chain_free_host_error(host: str) -> None:
701703
connection_string = f"chronicle://PRIVATE_CLIENT:PRIVATE_SECRET@{host}"
702704
with pytest.raises(InvalidHostError) as caught:
@@ -712,7 +714,17 @@ def test_idna_conversion_failures_raise_a_chain_free_host_error(host: str) -> No
712714

713715

714716
@pytest.mark.parametrize(
715-
"host", ["example.com", "127.0.0.1", "ex\u034fample.com", "x\u2024y.é", "faß.de"]
717+
"host",
718+
[
719+
"example.com",
720+
"127.0.0.1",
721+
"ex\u034fample.com",
722+
"x\u2024y.é",
723+
"faß.de",
724+
"xς.example",
725+
"fi.example",
726+
"Dž.example",
727+
],
716728
)
717729
@pytest.mark.parametrize("trailing_dot", ["", "."])
718730
def test_rejects_idna_mappings_that_change_the_supplied_host(host: str, trailing_dot: str) -> None:
@@ -729,6 +741,28 @@ def test_rejects_idna_mappings_that_change_the_supplied_host(host: str, trailing
729741
assert caught.value.__context__ is None
730742

731743

744+
@pytest.mark.parametrize(
745+
"host",
746+
[
747+
"münchen.xn--mnchen-3ya",
748+
"例え.xn--zckzah",
749+
"bücher.xn--r8jz45g.example",
750+
"münchen.XN--MNCHEN-3YA.example",
751+
],
752+
)
753+
@pytest.mark.parametrize("host_case", ["supplied", "upper"])
754+
@pytest.mark.parametrize("trailing_dot", ["", "."])
755+
def test_accepts_mixed_unicode_and_punycode_labels(host: str, host_case: str, trailing_dot: str) -> None:
756+
if host_case == "upper":
757+
host = host.upper()
758+
host += trailing_dot
759+
options = parse_connection_string(f"chronicle://id:secret@{host}")
760+
761+
assert options.host == host
762+
assert str(options) == f"chronicle://id:****@{host}:35000"
763+
assert parse_connection_string(str(options).replace("****", "secret")) == options
764+
765+
732766
@pytest.mark.parametrize("trailing_dot", ["", "."])
733767
def test_accepts_unicode_hosts_at_the_encoded_dns_length_limits(trailing_dot: str) -> None:
734768
host = ".".join(["é" * 57] * 3 + ["a" * 61]) + trailing_dot

0 commit comments

Comments
 (0)