d61550
From 2d4a3fee6de2fa45eb82169361918f759269b4ec Mon Sep 17 00:00:00 2001
d61550
From: Seth Michael Larson <sethmichaellarson@gmail.com>
d61550
Date: Wed, 26 May 2021 10:43:12 -0500
d61550
Subject: [PATCH] Improve performance of sub-authority splitting in URL
d61550
d61550
---
d61550
 src/urllib3/util/url.py |  8 +++++---
d61550
 test/test_util.py       | 10 ++++++++++
d61550
 2 files changed, 15 insertions(+), 3 deletions(-)
d61550
d61550
diff --git a/src/urllib3/util/url.py b/src/urllib3/util/url.py
d61550
index 6ff238fe3c..81a03da9e3 100644
d61550
--- a/src/urllib3/util/url.py
d61550
+++ b/src/urllib3/util/url.py
d61550
@@ -63,12 +63,12 @@
d61550
 BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT[2:-2] + "$")
d61550
 ZONE_ID_RE = re.compile("(" + ZONE_ID_PAT + r")\]$")
d61550
 
d61550
-SUBAUTHORITY_PAT = (u"^(?:(.*)@)?(%s|%s|%s)(?::([0-9]{0,5}))?$") % (
d61550
+_HOST_PORT_PAT = ("^(%s|%s|%s)(?::([0-9]{0,5}))?$") % (
d61550
     REG_NAME_PAT,
d61550
     IPV4_PAT,
d61550
     IPV6_ADDRZ_PAT,
d61550
 )
d61550
-SUBAUTHORITY_RE = re.compile(SUBAUTHORITY_PAT, re.UNICODE | re.DOTALL)
d61550
+_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL)
d61550
 
d61550
 UNRESERVED_CHARS = set(
d61550
     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~"
d61550
@@ -365,7 +365,9 @@ def parse_url(url):
d61550
             scheme = scheme.lower()
d61550
 
d61550
         if authority:
d61550
-            auth, host, port = SUBAUTHORITY_RE.match(authority).groups()
d61550
+            auth, _, host_port = authority.rpartition("@")
d61550
+            auth = auth or None
d61550
+            host, port = _HOST_PORT_RE.match(host_port).groups()
d61550
             if auth and normalize_uri:
d61550
                 auth = _encode_invalid_chars(auth, USERINFO_CHARS)
d61550
             if port == "":
d61550
diff --git a/test/test_util.py b/test/test_util.py
d61550
index a5b68a084b..88409e2d6c 100644
d61550
--- a/test/test_util.py
d61550
+++ b/test/test_util.py
d61550
@@ -438,6 +438,16 @@ def test_netloc(self, url, expected_netloc):
d61550
                 fragment="hash",
d61550
             ),
d61550
         ),
d61550
+        # Tons of '@' causing backtracking
d61550
+        ("https://" + ("@" * 10000) + "[", False),
d61550
+        (
d61550
+            "https://user:" + ("@" * 10000) + "example.com",
d61550
+            Url(
d61550
+                scheme="https",
d61550
+                auth="user:" + ("%40" * 9999),
d61550
+                host="example.com",
d61550
+            ),
d61550
+        ),
d61550
     ]
d61550
 
d61550
     @pytest.mark.parametrize("url, expected_url", url_vulnerabilities)