Skip to content

Commit 504abc6

Browse files
committed
Validate host grammar consistently across Python versions
1 parent 83c29b4 commit 504abc6

3 files changed

Lines changed: 115 additions & 13 deletions

File tree

‎Documentation/connection-strings.md‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,13 @@ chronicle://[<client-id>:<client-secret>@]<host>[:<port>][/][?skipTlsValidation=
2424
```
2525

2626
- The port defaults to `35000`.
27-
- The client id and client secret are percent-decoded. Encode reserved characters such as `@`, `:`, `/`, `?`, `#` and
28-
`%` in them.
29-
- An IPv6 host must be enclosed in brackets, for example `chronicle://id:secret@[::1]:35000`.
27+
- The client id and client secret are percent-decoded and must be valid UTF-8, without lone Unicode surrogates.
28+
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.
32+
- 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`.
3034
- Direct kernel connections default to TLS (`options.tls` is `True`).
3135
- Option names are case-insensitive.
3236

@@ -66,13 +70,17 @@ Every rejection is a subclass of `ConnectionStringError` (itself a `ValueError`)
6670
| --- | --- |
6771
| A scheme other than `chronicle://`, including `chronicle+srv://` | `UnsupportedSchemeError` |
6872
| No host | `MissingHostError` |
69-
| An invalid host, or more than one host | `InvalidHostError` |
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` |
7074
| A port that is not an integer from 1 to 65535 | `InvalidPortError` |
7175
| Only one of the client id and client secret, or an empty one | `IncompleteCredentialsError` |
72-
| Credentials that are not valid percent-encoded UTF-8 | `InvalidCredentialsEncodingError` |
76+
| Credentials containing invalid percent-encoded UTF-8 or lone Unicode surrogates | `InvalidCredentialsEncodingError` |
7377
| Client credentials combined with a non-empty `apiKey` | `AmbiguousAuthenticationError` |
7478
| 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` |
75-
| Whitespace or control characters | `MalformedConnectionStringError` |
79+
| Raw Unicode whitespace, control or format characters (categories `Cc`, `Cf`, `Zs`, `Zl`, `Zp`) | `MalformedConnectionStringError` |
80+
81+
Malformed bracketed hosts and unescaped brackets in the authority always raise `InvalidHostError` on every
82+
supported Python version. Other structurally invalid URLs raise `MalformedConnectionStringError`. Parser errors
83+
use fixed messages and discard underlying exception chains instead of echoing supplied credential text.
7684

7785
An empty `apiKey` is treated as absent. API key authentication (`apiKey=<key>` without credentials), `auth=none` and
7886
multiple hosts are not supported yet. They are rejected rather than ignored, so a connection never silently behaves

‎src/cratis_chronicle/connection_string.py‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343
_SCHEME = "chronicle"
4444
_REDACTED = "****"
45-
_HOST_NAME = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?\.?$")
45+
_HOST_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?")
4646
_FORBIDDEN_RAW_CATEGORIES = {"Cc", "Cf", "Zs", "Zl", "Zp"}
4747
_PORT = re.compile(r"^[0-9]+$")
4848
_API_KEY = "apikey"
@@ -145,7 +145,7 @@ def parse_connection_string(connection_string: str) -> ChronicleConnectionOption
145145
MalformedConnectionStringError: The raw string contains Unicode whitespace, control or format characters.
146146
UnsupportedSchemeError: The scheme is not ``chronicle``.
147147
MissingHostError: No host is given.
148-
InvalidHostError: The host is invalid, or more than one host is given.
148+
InvalidHostError: The host or its brackets are invalid, or more than one host is given.
149149
InvalidPortError: The port is not an integer between 1 and 65535.
150150
AmbiguousAuthenticationError: Credentials are combined with a non-empty ``apiKey``.
151151
UnsupportedOptionError: A path, fragment, or query parameter is given that is not supported yet, or
@@ -159,10 +159,14 @@ def parse_connection_string(connection_string: str) -> ChronicleConnectionOption
159159
if any(unicodedata.category(character) in _FORBIDDEN_RAW_CATEGORIES for character in connection_string):
160160
raise MalformedConnectionStringError("The connection string must not contain whitespace or control characters")
161161

162-
scheme, separator, _ = connection_string.partition("://")
162+
scheme, separator, authority_and_suffix = connection_string.partition("://")
163163
if not separator or scheme.lower() != _SCHEME:
164164
raise UnsupportedSchemeError(f"The connection string scheme must be '{_SCHEME}://'")
165165

166+
# Validate brackets before urlsplit, whose bracket checks vary between supported Python versions.
167+
authority = re.split(r"[/?#]", authority_and_suffix, maxsplit=1)[0]
168+
_validate_brackets(authority)
169+
166170
# The sanitised error is raised outside the except block so that neither __cause__ nor __context__ keeps the
167171
# original exception, whose message and traceback frames can contain the credentials.
168172
try:
@@ -193,12 +197,23 @@ def parse_connection_string(connection_string: str) -> ChronicleConnectionOption
193197
)
194198

195199

200+
def _validate_brackets(authority: str) -> None:
201+
user_info, _, host_and_port = authority.rpartition("@")
202+
if "[" in user_info or "]" in user_info:
203+
raise InvalidHostError("Brackets are only supported around an IPv6 host")
204+
if "[" in host_and_port or "]" in host_and_port:
205+
if not host_and_port.startswith("[") or host_and_port.count("[") != 1 or host_and_port.count("]") != 1:
206+
raise InvalidHostError("An IPv6 host must be enclosed in one pair of brackets")
207+
_parse_host_and_port(host_and_port)
208+
209+
196210
def _parse_host_and_port(host_and_port: str) -> tuple[str, int]:
197211
if host_and_port.startswith("["):
198212
closing = host_and_port.find("]")
199213
if closing == -1:
200214
raise InvalidHostError("An IPv6 address must be closed with ']'")
201-
host = host_and_port[1:closing]
215+
# RFC 6874 encodes the zone delimiter as %25; also accept the raw delimiter without changing the zone id.
216+
host = host_and_port[1:closing].replace("%25", "%", 1)
202217
remainder = host_and_port[closing + 1 :]
203218
if remainder and not remainder.startswith(":"):
204219
raise InvalidHostError("Unexpected text after the IPv6 address")
@@ -221,7 +236,13 @@ def _parse_host_and_port(host_and_port: str) -> tuple[str, int]:
221236
port_text = port_text_value if has_port else None
222237
if not host:
223238
raise MissingHostError("The connection string does not name a host")
224-
if not _HOST_NAME.match(host):
239+
host_name = host.removesuffix(".")
240+
if len(host_name) > 253:
241+
raise InvalidHostError("The host name must not exceed 253 characters")
242+
labels = host_name.split(".")
243+
if any(not 1 <= len(label) <= 63 for label in labels):
244+
raise InvalidHostError("Host name labels must contain between 1 and 63 characters")
245+
if any(not _HOST_LABEL.fullmatch(label) for label in labels):
225246
raise InvalidHostError("The host contains characters that are not valid in a host name")
226247

227248
return host, _parse_port(port_text)

‎tests/test_connection_string.py‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ def test_parses_an_ipv4_host() -> None:
108108
("chronicle://id:caf%C3%A9@localhost", "id", "café"),
109109
("chronicle://id:a+b@localhost", "id", "a+b"),
110110
("chronicle://id:se%3Acret@localhost", "id", "se:cret"),
111+
("chronicle://i%5Bd%5D:se%5Bcret%5D@localhost", "i[d]", "se[cret]"),
111112
],
112113
)
113114
def test_preserves_percent_encoded_credentials(connection_string: str, client_id: str, client_secret: str) -> None:
@@ -209,7 +210,7 @@ def test_rejects_a_missing_host(connection_string: str) -> None:
209210
],
210211
)
211212
def test_rejects_an_invalid_host(connection_string: str) -> None:
212-
with pytest.raises((InvalidHostError, MalformedConnectionStringError)):
213+
with pytest.raises(InvalidHostError):
213214
parse_connection_string(connection_string)
214215

215216

@@ -462,7 +463,7 @@ def test_accepts_an_absolute_host_name_with_a_trailing_dot(host: str) -> None:
462463

463464
@pytest.mark.parametrize("host", [".", "a..", ".a", "a.-"])
464465
def test_rejects_a_malformed_trailing_dot_host(host: str) -> None:
465-
with pytest.raises((InvalidHostError, MissingHostError)):
466+
with pytest.raises(InvalidHostError):
466467
parse_connection_string(f"chronicle://id:secret@{host}")
467468

468469

@@ -548,6 +549,78 @@ def test_preserves_percent_encoded_unicode_whitespace_control_and_format_charact
548549
assert str(options)
549550

550551

552+
@pytest.mark.parametrize(
553+
"authority",
554+
[
555+
"id:secret@[not-an-address]",
556+
"id:secret@[]",
557+
"id:secret@[::1",
558+
"id:secret@::1]",
559+
"id:secret@[[::1]]",
560+
"id:secret@[::1]]",
561+
"id:secret@[::1]x",
562+
"id:secret@x[::1]",
563+
"id:secret@[::1]:80]",
564+
"id:se[cret@localhost",
565+
"id:se]cret@localhost",
566+
"i[d:secret@localhost",
567+
"id:secret@[127.0.0.1]",
568+
"id:secret@[::1%]",
569+
"id:secret@[::1%25]",
570+
],
571+
)
572+
def test_invalid_brackets_raise_a_host_error_before_urlsplit(authority: str, monkeypatch: pytest.MonkeyPatch) -> None:
573+
def unexpected_urlsplit(value: str) -> None:
574+
pytest.fail("Invalid brackets must be rejected before calling urlsplit")
575+
576+
monkeypatch.setattr("cratis_chronicle.connection_string.urlsplit", unexpected_urlsplit)
577+
connection_string = f"chronicle://{authority}"
578+
with pytest.raises(InvalidHostError) as caught:
579+
parse_connection_string(connection_string)
580+
581+
assert "secret" not in str(caught.value)
582+
assert "secret" not in repr(caught.value)
583+
assert caught.value.__cause__ is None
584+
assert caught.value.__context__ is None
585+
586+
587+
@pytest.mark.parametrize(
588+
"host",
589+
[
590+
"a..b",
591+
"a.-b",
592+
"a-.b",
593+
"a" * 64,
594+
"a" * 64 + ".",
595+
".".join(["a" * 63] * 4),
596+
".".join(["a" * 63] * 3 + ["a" * 62]),
597+
".".join(["a" * 63] * 3 + ["a" * 62]) + ".",
598+
],
599+
)
600+
def test_rejects_invalid_dns_label_and_total_lengths(host: str) -> None:
601+
with pytest.raises(InvalidHostError):
602+
parse_connection_string(f"chronicle://id:secret@{host}")
603+
604+
605+
@pytest.mark.parametrize(
606+
"host",
607+
["a", "a" * 63, ".".join(["a" * 63] * 3 + ["a" * 61])],
608+
)
609+
@pytest.mark.parametrize("trailing_dot", ["", "."])
610+
def test_accepts_dns_label_and_total_length_limits(host: str, trailing_dot: str) -> None:
611+
host += trailing_dot
612+
assert parse_connection_string(f"chronicle://id:secret@{host}").host == host
613+
614+
615+
@pytest.mark.parametrize("host", ["fe80::1%eth0", "fe80::1%25eth0"])
616+
def test_normalises_an_ipv6_zone_delimiter(host: str) -> None:
617+
options = parse_connection_string(f"chronicle://id:secret@[{host}]:35001")
618+
619+
assert options.host == "fe80::1%eth0"
620+
assert str(options) == "chronicle://id:****@[fe80::1%eth0]:35001"
621+
assert parse_connection_string(str(options).replace("****", "secret")) == options
622+
623+
551624
def test_an_invalid_ipv6_host_error_does_not_retain_the_input_in_its_chain() -> None:
552625
secret = "super-secret"
553626
with pytest.raises(InvalidHostError) as caught:

0 commit comments

Comments
 (0)