Skip to content
Myr

Cleanup URL percent-encoding behavior. (#2990)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Replace path_query_fragment encoding tests * Remove replaced test cases * Fix test case to use correct hex sequence for 'abc' * Fix 'quote' behaviour so we don't double-escape. * Add '/' to safe chars in query strings * Update docstring * Linting * Update outdated comment. * Revert unrelated change ---------

authored by Tom Christie · committed by GitHub · parent 3b9060e · Browse files · 2 files+113 added−42 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com>

Diff stats

2 files+113 added−42 removed

  • tests:+70 added−34 removed
  • other:+43 added−8 removed

2 files+113 added−42 removed

modified:httpx/_urlparse.py+43 added-8 removed
258 unmodified lines
259260 # For 'path' we need to drop ? and # from the GEN_DELIMS set.261 parsed_path: str = quote(path, safe=SUB_DELIMS + ":/[]@")262 # For 'query' we need to drop '#' from the GEN_DELIMS set.263 # We also exclude '/' because it is more robust to replace it with a percent264 # encoding despite it not being a requirement of the spec.263 parsed_query: typing.Optional[str] = (266 None if query is None else quote(query, safe=SUB_DELIMS + ":?[]@")264 None if query is None else quote(query, safe=SUB_DELIMS + ":/?[]@")265 )266 # For 'fragment' we can include all of the GEN_DELIMS set.267 parsed_fragment: typing.Optional[str] = (268 None if fragment is None else quote(fragment, safe=SUB_DELIMS + ":/?#[]@")
160 unmodified lines
429 for char in string:430 if char not in NON_ESCAPED_CHARS:431 return False432435 # Any '%' characters must be valid '%xx' escape sequences.436 return string.count("%") == len(PERCENT_ENCODED_REGEX.findall(string))433 return True434435439def quote(string: str, safe: str = "/") -> str:436def percent_encoded(string: str, safe: str = "/") -> str:437 """441 Use percent-encoding to quote a string if required.438 Use percent-encoding to quote a string.439 """440 if is_safe(string, safe=safe):441 return string442
2 unmodified lines
445 [char if char in NON_ESCAPED_CHARS else percent_encode(char) for char in string]446 )447448449def quote(string: str, safe: str = "/") -> str:450 """451 Use percent-encoding to quote a string, omitting existing '%xx' escape sequences.452453 See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1454455 * `string`: The string to be percent-escaped.456 * `safe`: A string containing characters that may be treated as safe, and do not457 need to be escaped. Unreserved characters are always treated as safe.458 See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3459 """460 parts = []461 current_position = 0462 for match in re.finditer(PERCENT_ENCODED_REGEX, string):463 start_position, end_position = match.start(), match.end()464 matched_text = match.group(0)465 # Add any text up to the '%xx' escape sequence.466 if start_position != current_position:467 leading_text = string[current_position:start_position]468 parts.append(percent_encoded(leading_text, safe=safe))469470 # Add the '%xx' escape sequence.471 parts.append(matched_text)472 current_position = end_position473474 # Add any text after the final '%xx' escape sequence.475 if current_position != len(string):476 trailing_text = string[current_position:]477 parts.append(percent_encoded(trailing_text, safe=safe))478479 return "".join(parts)480481482def urlencode(items: typing.List[typing.Tuple[str, str]]) -> str:483 """484 We can use a much simpler version of the stdlib urlencode here because485 we don't need to handle a bunch of different typing cases, such as bytes vs str.
7 unmodified lines
493 - https://github.com/encode/httpx/issues/2536494 - https://github.com/encode/httpx/issues/2721495 - https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode496 """467 return "&".join([quote(k, safe="") + "=" + quote(v, safe="") for k, v in items])497 return "&".join(498 [499 percent_encoded(k, safe="") + "=" + percent_encoded(v, safe="")500 for k, v in items501 ]502 )
modified:tests/models/test_url.py+70 added-34 removed
68 unmodified lines
6970# Tests for percent encoding across path, query, and fragment...717273def test_path_percent_encoding():74 # Test percent encoding for SUB_DELIMS ALPHA NUM and allowable GEN_DELIMS75 url = httpx.URL("https://example.com/!$&'()*+,;= abc ABC 123 :/[]@")76 assert url.raw_path == b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@"77 assert url.path == "/!$&'()*+,;= abc ABC 123 :/[]@"78 assert url.query == b""79 assert url.fragment == ""73@pytest.mark.parametrize(74 "url,raw_path,path,query,fragment",75 [76 # URL with unescaped chars in path.77 (78 "https://example.com/!$&'()*+,;= abc ABC 123 :/[]@",79 b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",80 "/!$&'()*+,;= abc ABC 123 :/[]@",81 b"",82 "",83 ),84 # URL with escaped chars in path.85 (86 "https://example.com/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",87 b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",88 "/!$&'()*+,;= abc ABC 123 :/[]@",89 b"",90 "",91 ),92 # URL with mix of unescaped and escaped chars in path.93 # WARNING: This has the incorrect behaviour, adding the test as an interim step.94 (95 "https://example.com/ %61%62%63",96 b"/%20%61%62%63",97 "/ abc",98 b"",99 "",100 ),101 # URL with unescaped chars in query.102 (103 "https://example.com/?!$&'()*+,;= abc ABC 123 :/[]@?",104 b"/?!$&'()*+,;=%20abc%20ABC%20123%20:/[]@?",105 "/",106 b"!$&'()*+,;=%20abc%20ABC%20123%20:/[]@?",107 "",108 ),109 # URL with escaped chars in query.110 (111 "https://example.com/?!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",112 b"/?!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",113 "/",114 b"!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",115 "",116 ),117 # URL with mix of unescaped and escaped chars in query.118 (119 "https://example.com/?%20%97%98%99",120 b"/?%20%97%98%99",121 "/",122 b"%20%97%98%99",123 "",124 ),125 # URL encoding characters in fragment.126 (127 "https://example.com/#!$&'()*+,;= abc ABC 123 :/[]@?#",128 b"/",129 "/",130 b"",131 "!$&'()*+,;= abc ABC 123 :/[]@?#",132 ),133 ],134)135def test_path_query_fragment(url, raw_path, path, query, fragment):136 url = httpx.URL(url)137 assert url.raw_path == raw_path138 assert url.path == path139 assert url.query == query140 assert url.fragment == fragment14114282def test_query_percent_encoding():83 # Test percent encoding for SUB_DELIMS ALPHA NUM and allowable GEN_DELIMS84 url = httpx.URL("https://example.com/?!$&'()*+,;= abc ABC 123 :/[]@" + "?")85 assert url.raw_path == b"/?!$&'()*+,;=%20abc%20ABC%20123%20:%2F[]@?"86 assert url.path == "/"87 assert url.query == b"!$&'()*+,;=%20abc%20ABC%20123%20:%2F[]@?"88 assert url.fragment == ""899091def test_fragment_percent_encoding():92 # Test percent encoding for SUB_DELIMS ALPHA NUM and allowable GEN_DELIMS93 url = httpx.URL("https://example.com/#!$&'()*+,;= abc ABC 123 :/[]@" + "?#")94 assert url.raw_path == b"/"95 assert url.path == "/"96 assert url.query == b""97 assert url.fragment == "!$&'()*+,;= abc ABC 123 :/[]@?#"9899143def test_url_query_encoding():144 """102 URL query parameters should use '%20' to encoding spaces,145 URL query parameters should use '%20' for encoding spaces,146 and should treat '/' as a safe character. This behaviour differs147 across clients, but we're matching browser behaviour here.148149 See https://github.com/encode/httpx/issues/2536150 and https://github.com/encode/httpx/discussions/2460151 """152 url = httpx.URL("https://www.example.com/?a=b c&d=e/f")110 assert url.raw_path == b"/?a=b%20c&d=e%2Ff"153 assert url.raw_path == b"/?a=b%20c&d=e/f"154155 url = httpx.URL("https://www.example.com/", params={"a": "b c", "d": "e/f"})156 assert url.raw_path == b"/?a=b%20c&d=e%2Ff"157158116def test_url_with_url_encoded_path():117 url = httpx.URL("https://www.example.com/path%20to%20somewhere")118 assert url.path == "/path to somewhere"119 assert url.query == b""120 assert url.raw_path == b"/path%20to%20somewhere"121122159def test_url_params():160 url = httpx.URL("https://example.org:123/path/to/somewhere", params={"a": "123"})161 assert str(url) == "https://example.org:123/path/to/somewhere?a=123"162 assert url.params == httpx.QueryParams({"a": "123"})
680 unmodified lines