Skip to content

Commit 5355793

Browse files
miss-islingtonkenballus
authored andcommitted
pythongh-99418: Make urllib.parse.urlparse enforce that a scheme must begin with an alphabetical ASCII character. (pythonGH-99421)
Prevent urllib.parse.urlparse from accepting schemes that don't begin with an alphabetical ASCII character. RFC 3986 defines a scheme like this: `scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )` RFC 2234 defines an ALPHA like this: `ALPHA = %x41-5A / %x61-7A` The WHATWG URL spec defines a scheme like this: `"A URL-scheme string must be one ASCII alpha, followed by zero or more of ASCII alphanumeric, U+002B (+), U+002D (-), and U+002E (.)."` (cherry picked from commit 439b9cf) Co-authored-by: Ben Kallus <49924171+kenballus@users.noreply.github.com>
1 parent 8e41e91 commit 5355793

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

Lib/test/test_urlparse.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,24 @@ def test_attributes_bad_port(self):
735735
with self.assertRaises(ValueError):
736736
p.port
737737

738+
def test_attributes_bad_scheme(self):
739+
"""Check handling of invalid schemes."""
740+
for bytes in (False, True):
741+
for parse in (urllib.parse.urlsplit, urllib.parse.urlparse):
742+
for scheme in (".", "+", "-", "0", "http&", "६http"):
743+
with self.subTest(bytes=bytes, parse=parse, scheme=scheme):
744+
url = scheme + "://www.example.net"
745+
if bytes:
746+
if url.isascii():
747+
url = url.encode("ascii")
748+
else:
749+
continue
750+
p = parse(url)
751+
if bytes:
752+
self.assertEqual(p.scheme, b"")
753+
else:
754+
self.assertEqual(p.scheme, "")
755+
738756
def test_attributes_without_netloc(self):
739757
# This example is straight from RFC 3261. It looks like it
740758
# should allow the username, hostname, and port to be filled

Lib/urllib/parse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ def urlsplit(url, scheme='', allow_fragments=True):
452452
clear_cache()
453453
netloc = query = fragment = ''
454454
i = url.find(':')
455-
if i > 0:
455+
if i > 0 and url[0].isascii() and url[0].isalpha():
456456
if url[:i] == 'http': # optimize the common case
457457
url = url[i+1:]
458458
if url[:2] == '//':
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix bug in :func:`urllib.parse.urlparse` that causes URL schemes that begin
2+
with a digit, a plus sign, or a minus sign to be parsed incorrectly.

0 commit comments

Comments
 (0)