Skip to content

Parse and validate chronicle:// connection strings - #33

Open
woksin wants to merge 16 commits into
mainfrom
feature/connection-string-parser
Open

woksin wants to merge 16 commits into
mainfrom
feature/connection-string-parser

Conversation

@woksin

@woksin woksin commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Added

  • parse_connection_string() and ChronicleConnectionOptions.parse() parse a chronicle://[<client-id>:<client-secret>@]<host>[:<port>] connection string into immutable, typed ChronicleConnectionOptions without opening a connection. The port defaults to 35000, credentials are percent-decoded, and TLS is on by default. (Parse and validate Chronicle connection strings #2)
  • A connection string without credentials uses the development credentials, so chronicle://localhost:35000 equals chronicle://chronicle-dev-client:chronicle-dev-secret@localhost:35000, as in the .NET client. The values are exported as DEVELOPMENT_CLIENT_ID and DEVELOPMENT_CLIENT_SECRET. A partial set of credentials is rejected. (Parse and validate Chronicle connection strings #2)
  • skipTlsValidation is parsed into skip_tls_validation, which defaults to True like the .NET client. TLS stays on, and skipTlsValidation=false requires a verifiable certificate. (Parse and validate Chronicle connection strings #2)
  • Typed ConnectionStringError subclasses reject missing hosts, invalid ports, incomplete credentials, credentials combined with a non-empty apiKey, unsupported schemes and unsupported options such as auth=..., a non-empty apiKey without credentials, and other query parameters. An empty apiKey is treated as absent. (Parse and validate Chronicle connection strings #2)
  • str() and repr() of the parsed options never expose the client secret.

@woksin woksin self-assigned this Sep 30, 2026
@woksin woksin added the minor Backward-compatible capability addition label Sep 30, 2026
@woksin

woksin commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator Author

Design decisions for reviewers (the issue left these open):

  • Credentials are required in this first shape. A string with no credentials, or only one of client id and secret, raises IncompleteCredentialsError.
  • "Ambiguous authentication" is client credentials combined with an apiKey or auth query parameter (the selectors in the shared connection-string grammar). Used alone, apiKey and auth=none are rejected as unsupported options for now.
  • Every other query parameter (including skipTlsValidation), multiple hosts, chronicle+srv, a non-root path and a fragment raise UnsupportedOptionError/InvalidHostError/UnsupportedSchemeError. The client guide says the TLS relaxation API is a public API decision for this issue; this PR does not make it, so TLS is always on (tls=True).
  • Local gate: ruff format --check ., ruff check ., mypy src, pytest, python -m build, twine check all pass on Python 3.14.7. Python 3.10-3.13 were not available locally; CI covers them.

@woksin
woksin requested a review from einari September 30, 2026 23:36
@woksin

woksin commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@einari this needs your code-owner review to merge (branch protection requires a reviewer other than the author). Could you take a look?

The UnicodeDecodeError names the offending byte of the client secret. Raise
InvalidCredentialsEncodingError outside the handler so neither __cause__ nor
__context__ carries it.
@einari

einari commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Independent review (prerequisite for OAuth #3, authenticated append #4, parity #36): no blocking defects. One narrow hardening pushed as ba6e10d: InvalidCredentialsEncodingError no longer chains the decoder UnicodeDecodeError (its message names the offending byte of the secret); a spec asserts __cause__/__context__ are None. Note: the description's line about TLS always on predates the later commit; skip_tls_validation now defaults to True as in the .NET builder. Local: ruff, mypy, 148 pytest, build and twine check pass on 3.10-3.14.

@einari

einari commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Independent review passes after secret-safe exception hardening;148 tests/mypy pass on3.10-3.14 and hosted checks green atba6e10d. Current merge is legitimately protected (code-owner review + last-push approval), so I will not bypass it. @woksin please coordinate the protected review/last-push requirement; runtime#3/#4 is proceeding stacked on this accepted API while review is pending. Source of evidence: event-source-worktrees/logs/python-parser-review.status.md.

einari
einari previously approved these changes Oct 3, 2026

@einari einari left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved after independent automated review at ba6e10d:148 specs and strict typing across Python3.10-3.14 plus hosted CI. Secret decoder exceptions hardened; options immutable and credentials redacted. This approval does not bypass code-owner or last-push protections; preserve those gates. Runtime uses production certificate/hostname validation despite parser dev-default skipTlsValidation.

@woksin

woksin commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

Cross-provider review findings and fixes (commit cbaf453):

  1. Major: credential leak via chained urlsplit ValueError. The sanitised MalformedConnectionStringError is now raised outside the except block with from None, so neither __cause__ nor __context__ keeps the original exception. Test checks the formatted traceback and the chain for chronicle://id:super-secret@host/bad.
  2. Minor: trailing-dot absolute host names rejected. The host pattern now allows one terminal root dot (kernel.example.com.), preserved as given like the .NET parser. Malformed dots (., a.., .a) are still rejected; tests cover both.
  3. Minor: 4,400-digit port raised a plain ValueError. Ports with more than five significant digits are rejected as InvalidPortError before int() conversion; leading zeros (00080) still parse. Tests added.

Local: ruff format/check, mypy and pytest pass on Python 3.14 only (the other versions are not installed locally). CI passes on 3.10 to 3.14.

@woksin

woksin commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Addressed the second re-review in normal commits 611dff1 and 299199c, and the full third review in 83c29b4 and 504abc6. The fourth review is addressed in 1ce1d0d, e5196b4, and e11cec5. The fifth review is addressed in 3fba971. The sixth review is addressed in dbd2cbc. The seventh review is addressed in b36373a. The history used by stacked draft #39 is preserved.

  • Unsupported query parameters now produce a generic message without the supplied name. The unescaped ? credential-fragment reproduction and its percent-encoded variant have regression coverage for the message, exception repr, formatted traceback, and absence of cause/context.
  • Ports are normalised once before both the significant-digit guard and integer conversion. Tests cover 4,400 leading zeros followed by 80 (accepted as port 80) and 4,400 zeros alone (typed InvalidPortError).

Third-review fixes:

  • Both decoded credential fields are checked for U+D800–U+DFFF before options are returned. Raw surrogates, raw surrogates alongside percent escapes, and percent-encoded surrogate bytes all raise the same static, chain-free InvalidCredentialsEncodingError. Tests check both fields, the message, exception repr, formatted traceback and cause/context.
  • The raw connection string rejects Unicode categories Cc, Cf, Zs, Zl, and Zp, covering U+0080, U+0085, U+00A0, U+2003, U+2028, U+200E and U+2029. Explicitly percent-encoded credential characters remain supported as required by the review; tests cover both rejection and preservation in both fields.
  • Authority brackets and the bracketed IPv6 host are validated before urlsplit, making invalid/misplaced brackets consistently raise InvalidHostError independently of Python's changing bracket checks. Tests assert the rejection occurs before urlsplit; percent-encoded credential brackets still work. The documentation table now states the deterministic contract.
  • DNS labels must be non-empty, 1–63 characters long, and begin/end with a letter or digit; the full name must be at most 253 characters excluding a trailing root dot. Tests exercise invalid names and both sides of the length boundaries, with the root dot preserved.
  • The report's IPv6-zone finding is addressed by normalising the %25 zone delimiter: [fe80::1%eth0] and [fe80::1%25eth0] now return the same host. Tests and docs cover both spellings and the redacted string round-trip.

Fourth-review fixes:

  • IPv6 zone ids must match [A-Za-z0-9._~-]+ after %25 delimiter normalisation. Empty zones, lone surrogates, colons, non-ASCII text and other disallowed characters raise a fixed, chain-free InvalidHostError. Tests cover both delimiter spellings, accepted characters, exception repr, formatted traceback and chaining.
  • Added Cn to the rejected raw Unicode categories. U+0890, U+0891 and U+13439–U+1343F are therefore rejected whether the interpreter considers them unassigned or format characters. Tests cover both credential fields, an always-unassigned character, and preservation through explicit percent encoding.
  • Checked the .NET builder's actual source rather than inferring its behaviour from Uri: ParseServerAddress/ServerAddresses/Host store the supplied host unchanged, and ChronicleServerAddress adds no hostname validation. Thus Unicode IDNs are accepted and preserved by that client. Python now accepts Unicode and ASCII punycode forms too, validates DNS limits against the standard-library IDNA-encoded ASCII form, and preserves the supplied host/trailing dot. Tests cover münchen.example, 例え.テスト, bücher.example, their punycode forms, encoded DNS-length boundaries, and chain-free codec failures. Documentation states this contract.

Fifth-review fix:

  • Each non-ASCII label in a host must round-trip through IDNA to its NFC-normalised, lowercase spelling. Other nameprep mappings now raise the same fixed, chain-free InvalidHostError: fullwidth ASCII, fullwidth IPv4, U+034F deletion, U+2024 dot mapping and ß → ss all have regression coverage, with and without a trailing root dot. Tests check the message, repr, formatted traceback and cause/context.
  • Validation lowercases before encoding so uppercase ASCII labels in a Unicode host also round-trip correctly. münchen.example, its decomposed NFC-equivalent spelling, 例え.テスト, bücher.example, their uppercase forms and their punycode forms still parse while preserving the supplied spelling and trailing dot. A decoder-failure regression also verifies that the new round-trip codec cannot expose an exception chain. Documentation states the identity-mapping rule.

Sixth-review fix:

  • IDNA identity checks now operate per label and compare only labels containing non-ASCII characters. ASCII punycode labels in mixed hosts are still decoded for validation, but are not compared to their decoded Unicode spelling. This restores mixed Unicode/punycode hosts without relaxing the nameprep-mapping guard.
  • Parametrised tests cover all four reported mixed hosts in supplied/uppercase spelling, with and without a trailing dot, preserving the host and redacted string round-trip. Invalid ASCII punycode in mixed hosts still raises a fixed, chain-free host error. All earlier rejection cases remain; explicit final-sigma, ligature and titlecase-digraph regressions now cover the additional confusables confirmed by review. Documentation explains the per-label contract.

Seventh-review fixes:

  • The per-label validator now runs whenever any label starts with xn-- (case-insensitively), even in all-ASCII hosts. Invalid or non-canonical punycode consistently raises the existing fixed, chain-free InvalidHostError; Unicode label identity checks are unchanged. Documentation now states that every punycode label is decoded for validation.
  • Added the requested non-empty failures: münchen.xn--zz, münchen.xn--mnchen-3ya-, münchen.xn--zca, xn--zz.com, xn--zca.de, plus an uppercase invalid prefix. All check the fixed message, repr, formatted traceback and empty cause/context. Valid all-ASCII punycode fixtures include xn--mnchen-3ya.de, Japanese multi-label punycode and a punycode label following www, with upper/lower case and trailing-dot variants; supplied spelling and redacted round-trips remain intact.

Diagnostic audit of src/cratis_chronicle/connection_string.py:

  • Checked every explicit raise in the public parser and the host/port, query, and credential helpers: input type, whitespace/control characters, scheme, malformed URL, paths/fragments, IPv6 brackets/suffixes/validation, multiple or missing hosts, invalid host characters, port syntax/length/range, empty queries, auth, apiKey, authentication ambiguity, TLS boolean values, unknown options, incomplete credentials, unescaped credential colons, and invalid UTF-8. All messages now use fixed text or the fixed scheme constant, not supplied names, values, hosts, credentials, or type names. The non-string TypeError was additionally made generic because a caller-defined type name can itself contain sensitive text.
  • Checked standard-library failure paths: urlsplit and UTF-8 decoding already discard their original exception chains; the IPv6 validator now also raises the generic error outside its handler, retaining neither cause nor context. Port conversion is bounded after normalisation; query decoding uses replacement rather than exposing decoding failures.
  • Checked exception repr (inherited from ValueError/TypeError, using the now-sanitised arguments), the options dataclass repr (client_secret remains excluded), and options str/format (secret remains replaced by ****). The public host/client-id fields retain their existing rendering behaviour. Added message/repr/traceback checks across the rejection categories and the IPv6-helper/type-name paths.
  • Rechecked the new Unicode, bracket, zone and DNS/IDNA rejections: all messages are static and preserve neither a decoder, an IPv6-validator exception nor an IDNA-codec exception. Surrogates cannot reach the parsed options' client-id quoting path or survive in a parsed IPv6 zone.
  • Checked for logging: the module imports no logger and contains no log calls.

Local CI-equivalent commands passed on the only installed supported version, Python 3.14.7: ruff format --check ., ruff check ., mypy src, pytest (403 passing), python -m build, and python -m twine check dist/*. Python 3.10–3.13 are not installed locally; the hosted matrix covers them. No integration lane exists in this repository. Markdown lint passed with the workflow's globs plus exclusions for ignored local .ai-work and .venv directories; the cached CLI was used offline without installing tooling. Workflow/metadata inputs and the single minor release-intent label are unchanged.

Hosted CI at b36373a passed the full Python 3.10–3.14 matrix. Markdown verification and both metadata checks also passed.

No rebase or force-push was used. This remains unmerged pending non-author approval.

@woksin woksin reopened this Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor Backward-compatible capability addition

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants