Skip to content

Commit 439b9cf

Browse files
authored
gh-99418: Make urllib.parse.urlparse enforce that a scheme must begin with an alphabetical ASCII character. (#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 (.)."`
1 parent 50b0415 commit 439b9cf

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Lib/test/test_urlparse.py

+18
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,24 @@ def test_attributes_bad_port(self):
668668
with self.assertRaises(ValueError):
669669
p.port
670670

671+
def test_attributes_bad_scheme(self):
672+
"""Check handling of invalid schemes."""
673+
for bytes in (False, True):
674+
for parse in (urllib.parse.urlsplit, urllib.parse.urlparse):
675+
for scheme in (".", "+", "-", "0", "http&", "६http"):
676+
with self.subTest(bytes=bytes, parse=parse, scheme=scheme):
677+
url = scheme + "://www.example.net"
678+
if bytes:
679+
if url.isascii():
680+
url = url.encode("ascii")
681+
else:
682+
continue
683+
p = parse(url)
684+
if bytes:
685+
self.assertEqual(p.scheme, b"")
686+
else:
687+
self.assertEqual(p.scheme, "")
688+
671689
def test_attributes_without_netloc(self):
672690
# This example is straight from RFC 3261. It looks like it
673691
# should allow the username, hostname, and port to be filled

Lib/urllib/parse.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ def urlsplit(url, scheme='', allow_fragments=True):
460460
allow_fragments = bool(allow_fragments)
461461
netloc = query = fragment = ''
462462
i = url.find(':')
463-
if i > 0:
463+
if i > 0 and url[0].isascii() and url[0].isalpha():
464464
for c in url[:i]:
465465
if c not in scheme_chars:
466466
break
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)