Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Lib/test/test_urlparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1541,6 +1541,18 @@ def test_parse_qsl_errors(self):
with self.assertRaises(UnicodeDecodeError):
urllib.parse.parse_qsl('a=b', separator=b'\xa6')

def test_parse_qsl_strict_invalid_query_chars(self):
# gh-135523: RFC 3986 excludes '#', '[', ']', etc. from query
for qs in ['foo=#', 'foo=[bar]', 'a={b}', 'a=b c']:
with self.subTest(qs=qs):
self.assertRaises(ValueError, urllib.parse.parse_qsl,
qs, strict_parsing=True)
# bytes input
self.assertRaises(ValueError, urllib.parse.parse_qsl,
b'foo=#', strict_parsing=True)
# valid query chars accepted
urllib.parse.parse_qsl('a=1&b=2%20x', strict_parsing=True)

def test_urlencode_sequences(self):
# Other tests incidentally urlencode things; test non-covered cases:
# Sequence and object values.
Expand Down
20 changes: 20 additions & 0 deletions Lib/urllib/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,13 @@ def unquote(string, encoding='utf-8', errors='replace'):
return ''.join(_generate_unquoted_parts(string, encoding, errors))


# RFC 3986
_VALID_QUERY_CHARS = frozenset(
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
"-._~!$&'()*+,;=:@/?%"
)


def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace', max_num_fields=None, separator='&'):
"""Parse a query given as a string argument.
Expand Down Expand Up @@ -968,6 +975,19 @@ def _unquote(s):
if max_num_fields < num_fields:
raise ValueError('Max number of fields exceeded')

if strict_parsing:
if isinstance(qs, bytes):
qs_chars = {chr(b) for b in qs}
sep_chars = {chr(b) for b in separator}
else:
qs_chars = set(qs)
sep_chars = set(separator)
invalid = qs_chars - _VALID_QUERY_CHARS - sep_chars
if invalid:
raise ValueError(
"invalid query characters: %r" % ''.join(sorted(invalid))
)

r = []
for name_value in qs.split(separator):
if name_value or strict_parsing:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:func:`urllib.parse.parse_qsl` and :func:`urllib.parse.parse_qs` now reject
characters not valid per :rfc:`3986` when *strict_parsing* is ``True``.
Loading