Skip to content

Commit e11cec5

Browse files
committed
Accept Unicode IDN hosts while preserving their representation
1 parent e5196b4 commit e11cec5

3 files changed

Lines changed: 74 additions & 6 deletions

File tree

‎Documentation/connection-strings.md‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,16 @@ chronicle://[<client-id>:<client-secret>@]<host>[:<port>][/][?skipTlsValidation=
2626
- The port defaults to `35000`.
2727
- The client id and client secret are percent-decoded and must be valid UTF-8, without lone Unicode surrogates.
2828
Encode reserved characters such as `@`, `:`, `/`, `?`, `#`, `[`, `]` and `%` in them. Raw Unicode whitespace,
29-
control and format characters are rejected; explicitly percent-encoded credential characters are preserved.
30-
- Host names have non-empty labels of 1–63 characters, starting and ending with a letter or digit. The total name
31-
length is at most 253 characters, ignoring an optional trailing dot, which is preserved.
29+
control, format and unassigned characters are rejected; explicitly percent-encoded credential characters are
30+
preserved. Rejecting unassigned characters also rejects newly assigned format characters on older Python versions.
31+
- Internationalised host names are accepted as Unicode (`münchen.example`, `例え.テスト`) or ASCII punycode
32+
(`xn--mnchen-3ya.example`, `xn--r8jz45g.xn--zckzah`). The supplied representation is preserved, as in the .NET client.
33+
Host names are validated using their IDNA-encoded ASCII form: non-empty labels of 1–63 characters, starting and
34+
ending with a letter or digit, and at most 253 characters in total, ignoring an optional trailing dot, which is
35+
preserved.
3236
- An IPv6 host must be enclosed in brackets, for example `chronicle://id:secret@[::1]:35000`. For a scoped address,
33-
both `[fe80::1%eth0]` and `[fe80::1%25eth0]` produce the host `fe80::1%eth0`.
37+
both `[fe80::1%eth0]` and `[fe80::1%25eth0]` produce the host `fe80::1%eth0`. The zone id must be non-empty and contain
38+
only ASCII letters, digits or `._~-`.
3439
- Direct kernel connections default to TLS (`options.tls` is `True`).
3540
- Option names are case-insensitive.
3641

@@ -70,13 +75,13 @@ Every rejection is a subclass of `ConnectionStringError` (itself a `ValueError`)
7075
| --- | --- |
7176
| A scheme other than `chronicle://`, including `chronicle+srv://` | `UnsupportedSchemeError` |
7277
| No host | `MissingHostError` |
73-
| An invalid host, empty or over-long host name labels, a host name over 253 characters, invalid or misplaced brackets, or more than one host | `InvalidHostError` |
78+
| An invalid host or IDNA encoding, empty or over-long encoded host name labels, an encoded host name over 253 characters, invalid IPv6 zone ids, invalid or misplaced brackets, or more than one host | `InvalidHostError` |
7479
| A port that is not an integer from 1 to 65535 | `InvalidPortError` |
7580
| Only one of the client id and client secret, or an empty one | `IncompleteCredentialsError` |
7681
| Credentials containing invalid percent-encoded UTF-8 or lone Unicode surrogates | `InvalidCredentialsEncodingError` |
7782
| Client credentials combined with a non-empty `apiKey` | `AmbiguousAuthenticationError` |
7883
| A non-empty `apiKey` without credentials, any `auth=...`, a `skipTlsValidation` that is not `true` or `false`, any other query parameter, a path other than `/`, or a fragment | `UnsupportedOptionError` |
79-
| Raw Unicode whitespace, control or format characters (categories `Cc`, `Cf`, `Zs`, `Zl`, `Zp`) | `MalformedConnectionStringError` |
84+
| Raw Unicode whitespace, control, format or unassigned characters (categories `Cc`, `Cf`, `Cn`, `Zs`, `Zl`, `Zp`) | `MalformedConnectionStringError` |
8085

8186
Malformed bracketed hosts and unescaped brackets in the authority always raise `InvalidHostError` on every
8287
supported Python version. Other structurally invalid URLs raise `MalformedConnectionStringError`. Parser errors

‎src/cratis_chronicle/connection_string.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,8 @@ def _parse_host_and_port(host_and_port: str) -> tuple[str, int]:
244244
if not host:
245245
raise MissingHostError("The connection string does not name a host")
246246
host_name = host.removesuffix(".")
247+
if not host_name.isascii():
248+
host_name = _encode_idn_host(host_name)
247249
if len(host_name) > 253:
248250
raise InvalidHostError("The host name must not exceed 253 characters")
249251
labels = host_name.split(".")
@@ -255,6 +257,18 @@ def _parse_host_and_port(host_and_port: str) -> tuple[str, int]:
255257
return host, _parse_port(port_text)
256258

257259

260+
def _encode_idn_host(host: str) -> str:
261+
"""Validate Unicode DNS names through IDNA without changing the returned host representation."""
262+
try:
263+
ascii_host = host.encode("idna").decode("ascii")
264+
except UnicodeError:
265+
ascii_host = None
266+
if ascii_host is None:
267+
# The codec exception can contain the input host; do not retain it in cause or context.
268+
raise InvalidHostError("The host is not a valid internationalised host name")
269+
return ascii_host
270+
271+
258272
def _parse_port(port_text: str | None) -> int:
259273
if port_text is None:
260274
return DEFAULT_PORT

‎tests/test_connection_string.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,55 @@ def test_preserves_percent_encoded_unassigned_or_newly_assigned_format_character
671671
assert str(options)
672672

673673

674+
@pytest.mark.parametrize(
675+
("unicode_host", "ascii_host"),
676+
[
677+
("münchen.example", "xn--mnchen-3ya.example"),
678+
("例え.テスト", "xn--r8jz45g.xn--zckzah"),
679+
("bücher.example", "xn--bcher-kva.example"),
680+
],
681+
)
682+
@pytest.mark.parametrize("host_form", ["unicode", "punycode"])
683+
@pytest.mark.parametrize("trailing_dot", ["", "."])
684+
def test_accepts_idn_hosts_and_preserves_the_supplied_representation(
685+
unicode_host: str, ascii_host: str, host_form: str, trailing_dot: str
686+
) -> None:
687+
host = (unicode_host if host_form == "unicode" else ascii_host) + trailing_dot
688+
options = parse_connection_string(f"chronicle://id:secret@{host}")
689+
690+
assert options.host == host
691+
assert options.host.encode("idna").decode("ascii") == ascii_host + trailing_dot
692+
assert str(options) == f"chronicle://id:****@{host}:35000"
693+
694+
695+
@pytest.mark.parametrize("host", ["PRIVATE_HOST\ud800.example", "é" * 58 + ".example"])
696+
def test_idna_conversion_failures_raise_a_chain_free_host_error(host: str) -> None:
697+
connection_string = f"chronicle://PRIVATE_CLIENT:PRIVATE_SECRET@{host}"
698+
with pytest.raises(InvalidHostError) as caught:
699+
parse_connection_string(connection_string)
700+
701+
assert str(caught.value) == "The host is not a valid internationalised host name"
702+
for rendering in (str(caught.value), repr(caught.value), "".join(traceback.format_exception(caught.value))):
703+
assert "PRIVATE_HOST" not in rendering
704+
assert "PRIVATE_CLIENT" not in rendering
705+
assert "PRIVATE_SECRET" not in rendering
706+
assert caught.value.__cause__ is None
707+
assert caught.value.__context__ is None
708+
709+
710+
@pytest.mark.parametrize("trailing_dot", ["", "."])
711+
def test_accepts_unicode_hosts_at_the_encoded_dns_length_limits(trailing_dot: str) -> None:
712+
host = ".".join(["é" * 57] * 3 + ["a" * 61]) + trailing_dot
713+
assert parse_connection_string(f"chronicle://id:secret@{host}").host == host
714+
715+
716+
@pytest.mark.parametrize("trailing_dot", ["", "."])
717+
def test_rejects_unicode_hosts_beyond_the_encoded_total_dns_length_limit(trailing_dot: str) -> None:
718+
host = ".".join(["é" * 57] * 3 + ["a" * 62]) + trailing_dot
719+
with pytest.raises(InvalidHostError):
720+
parse_connection_string(f"chronicle://id:secret@{host}")
721+
722+
674723
def test_an_invalid_ipv6_host_error_does_not_retain_the_input_in_its_chain() -> None:
675724
secret = "super-secret"
676725
with pytest.raises(InvalidHostError) as caught:

0 commit comments

Comments
 (0)