Merge pull request #3695 from nateprewitt/idna_bypass
Before adoption: this commit came in with the history the project adopted, so no landing records it.
idna bypass
authored by Cory Benfield · committed by GitHub · parents 36c9c8c, a83685c · Browse files · 4 files·+52 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+52 added−4 removed
- tests:+27 added−0 removed
- other:+25 added−4 removed
Provenance
- Commit
5c45494- Tree
9791b17- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
36c9c8c- Parent 2
a83685c
4 files changed+52 added−4 removed
modified:requests/_internal_utils.py+16 added-1 removed
6 unmodified lines7 Provides utility functions that are consumed internally by Requests8 which depend on extremely few external helpers (such as compat)9 """10 11-from .compat import is_py2, builtin_str11+from .compat import is_py2, builtin_str, str12 13 14 def to_native_string(string, encoding='ascii'):15 """Given a string object, regardless of type, returns a representation of8 unmodified lines24 else:25 out = string.decode(encoding)26 27 return out28+29+30+def unicode_is_ascii(u_string):31+ """Determine if unicode string only contains ASCII characters.32+33+ :param str u_string: unicode string to check. Must be unicode34+ and not Python 2 `str`.35+ :rtype: bool36+ """37+ assert isinstance(u_string, str)38+ try:39+ u_string.encode('ascii')40+ return True41+ except UnicodeEncodeError:42+ return Falsemodified:requests/models.py+9 added-3 removed
28 unmodified lines29 DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)30 from .exceptions import (31 HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,32 ContentDecodingError, ConnectionError, StreamConsumedError)33-from ._internal_utils import to_native_string33+from ._internal_utils import to_native_string, unicode_is_ascii34 from .utils import (35 guess_filename, get_auth_from_url, requote_uri,36 stream_decode_response_unicode, to_key_val_list, parse_header_links,37 iter_slices, guess_json_utf, super_len, check_header_validity)329 unmodified lines367 368 if not host:369 raise InvalidURL("Invalid URL %r: No host supplied" % url)370 371- # Only want to apply IDNA to the hostname371+ # In general, we want to try IDNA encoding every hostname, as that372+ # allows users to automatically get the correct behaviour. However,373+ # we’re quite strict about IDNA encoding, so certain valid hostnames374+ # may fail to encode. On failure, we verify the hostname meets a375+ # minimum standard of only containing ASCII characters, and not starting376+ # with a wildcard (*), before allowing the unencoded hostname through.377 try:378 host = idna.encode(host, uts46=True).decode('utf-8')379 except (UnicodeError, idna.IDNAError):380+ if not unicode_is_ascii(host) or host.startswith(u'*'):375- raise InvalidURL('URL has an invalid label.')381+ raise InvalidURL('URL has an invalid label.')382 383 # Carefully reconstruct the network location384 netloc = auth or ''385 if netloc:521 unmodified linesmodified:tests/test_requests.py+14 added
2119 unmodified lines2120 'url,expected',2121 (2122 ('http://google.com', 'http://google.com/'),2123 (u'http://ジェーピーニック.jp', u'http://xn--hckqz9bzb1cyrb.jp/'),2124+ (u'http://xn--n3h.net/', u'http://xn--n3h.net/'),2125 (2126 u'http://ジェーピーニック.jp'.encode('utf-8'),2127 u'http://xn--hckqz9bzb1cyrb.jp/'2128 ),12 unmodified lines2141 (2142 u'http://Königsgäßchen.de/straße'.encode('utf-8'),2143 u'http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe'2144 ),2145+ (2146+ b'http://xn--n3h.net/',2147+ u'http://xn--n3h.net/'2148+ ),2149+ (2150+ b'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/',2151+ u'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/'2152+ ),2153+ (2154+ u'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/',2155+ u'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/'2156+ )2157 )2158 )2159 def test_preparing_url(self, url, expected):2160 r = requests.Request('GET', url=url)6 unmodified lines2167 b"http://*.google.com",2168 b"http://*",2169 u"http://*.google.com",2170 u"http://*",2171+ u"http://☃.net/"2172 )2173 )2174 def test_preparing_bad_url(self, url):2175 r = requests.Request('GET', url=url)19 unmodified linesmodified:tests/test_utils.py+13 added
15 unmodified lines16 requote_uri, select_proxy, should_bypass_proxies, super_len,17 to_key_val_list, to_native_string,18 unquote_header_value, unquote_unreserved,19 urldefragauth, add_dict_to_cookiejar)20+from requests._internal_utils import unicode_is_ascii21 22 from .compat import StringIO, cStringIO23 24 490 unmodified lines515 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')516 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')517 assert should_bypass_proxies(url) == expected518 519+520 @pytest.mark.parametrize(521 'cookiejar', (522 compat.cookielib.CookieJar(),523 RequestsCookieJar()6 unmodified lines530 'good': 'cookies'}531 cj = add_dict_to_cookiejar(cookiejar, cookiedict)532 cookies = dict((cookie.name, cookie.value) for cookie in cj)533 assert cookiedict == cookies534+535+536+@pytest.mark.parametrize(537+ 'value, expected', (538+ (u'test', True),539+ (u'æíöû', False),540+ (u'ジェーピーニック', False),541+ )542+)543+def test_unicode_is_ascii(value, expected):544+ assert unicode_is_ascii(value) is expected