From 4560d2adbca768d4fee1368ca866133c7ad95186 Mon Sep 17 00:00:00 2001 From: xgbtxy <115146404+xgbtxy@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:17:24 +0800 Subject: [PATCH] Preserve hostname when normalizing URIs with an empty port Allow zero-digit ports in PORT_RE per RFC 3986 section 3.2.3 and normalize empty port matches to None in URIMixin.authority_info() so normalize() omits the colon without dropping the host. --- src/rfc3986/_mixin.py | 3 +++ src/rfc3986/abnf_regexp.py | 2 +- tests/test_uri.py | 24 ++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/rfc3986/_mixin.py b/src/rfc3986/_mixin.py index b03b772..bdc2a28 100644 --- a/src/rfc3986/_mixin.py +++ b/src/rfc3986/_mixin.py @@ -69,6 +69,9 @@ def authority_info(self) -> _AuthorityInfo: # valid bytes, it is an InvalidAuthority. raise exc.InvalidAuthority(self.authority.encode(self.encoding)) + if matches.get("port") == "": + matches["port"] = None + return matches def _match_subauthority(self) -> t.Optional[t.Match[str]]: diff --git a/src/rfc3986/abnf_regexp.py b/src/rfc3986/abnf_regexp.py index b18d158..c717a21 100644 --- a/src/rfc3986/abnf_regexp.py +++ b/src/rfc3986/abnf_regexp.py @@ -134,7 +134,7 @@ USERINFO_RE = ( "^([" + UNRESERVED_RE + SUB_DELIMITERS_RE + ":]|%s)+" % (PCT_ENCODED) ) -PORT_RE = "[0-9]{1,5}" +PORT_RE = "[0-9]{0,5}" # #################### # Path Matcher Section diff --git a/tests/test_uri.py b/tests/test_uri.py index 4ae383c..c2f97e4 100644 --- a/tests/test_uri.py +++ b/tests/test_uri.py @@ -404,3 +404,27 @@ def test_wide_domain_bypass_check(): ref = URIReference.from_string(url) assert ref.scheme == "https" assert ref.host == "xdavidhu.me" + + +@pytest.mark.parametrize( + ("raw", "expected_host", "expected_normalized"), + [ + ("HTTP://example.com:/a", "example.com", "http://example.com/a"), + ( + "HTTPS://user@EXAMPLE.COM:/a/b/../c", + "EXAMPLE.COM", + "https://user@example.com/a/c", + ), + ("http://[::1]:/path", "[::1]", "http://[::1]/path"), + ], +) +def test_empty_port_preserves_host_on_normalize( + raw, expected_host, expected_normalized +): + """RFC 3986 section 3.2.3 & 6.2.3: empty port must preserve host.""" + ref = URIReference.from_string(raw) + assert ref.host == expected_host + assert ref.port is None + assert ref.authority_info()["host"] == expected_host + assert ref.authority_info()["port"] is None + assert ref.normalize().unsplit() == expected_normalized