Skip to content

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

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

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.

@albertedwardson

albertedwardson commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

just no.

@patchwright

Copy link
Copy Markdown
Author

Closing this — #261 (can_ada migration) already covers this case per its description ("closes #270"), and it's a more thorough fix than mine. Thanks for looking, and thanks @AdrianAtZyte for the broader rewrite.

@patchwright patchwright closed this Aug 6, 2026
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

2 participants