Skip to content

Fix canonicalize_url IDNA-encoding the port and userinfo of a non-ASCII host#270

Open
patchwright wants to merge 1 commit into
scrapy:masterfrom
patchwright:fix/canonicalize-url-idna-host-only
Open

Fix canonicalize_url IDNA-encoding the port and userinfo of a non-ASCII host#270
patchwright wants to merge 1 commit into
scrapy:masterfrom
patchwright:fix/canonicalize-url-idna-host-only

Conversation

@patchwright

Copy link
Copy Markdown

Fixes #222.

Problem

canonicalize_url runs IDNA encoding on the entire netloc, so when a non-ASCII host has a port (or userinfo), those parts get folded into the last IDNA label and mangled:

>>> canonicalize_url('https://тест.тест:33')
'https://xn--e1aybc.xn--:33-qdd4dec/'   # the :33 is corrupted

Expected:

'https://xn--e1aybc.xn--e1aybc:33/'

safe_url_string already handles host and port separately; only the canonicalize_url path (via _safe_ParseResult) was affected.

Fix

Add _idna_netloc, which applies IDNA to the host substring only and leaves any userinfo@ prefix and :port suffix verbatim. IPv6 literals are ASCII (IDNA is a no-op) so the bracketed host is returned untouched. Because IDNA is a no-op on ASCII, no existing ASCII-netloc behaviour changes. The existing UnicodeError fallback (too-long / missing labels) is preserved.

Tests

Added test_canonicalize_idns_with_port covering host+port, userinfo+port (userinfo stays case-sensitive), and the no-port case. Proven to fail on unpatched source (xn--33-mlc2cdc) and pass with the fix. Full suite: 359 passed, 0 failures; mypy + ruff clean.

Note: the trailing-multiple-dots addendum in #222 is left out of scope, as the reporter noted it may be standards-correct behaviour.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

canonicalize_url incorrectly handles port when using hostname that requires IDNA encoding

1 participant