Skip to content
Myr

Use rfc3986 for URL handling

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

authored by Tom Christie · committed by Tom Christie · parent fd9823e · Browse files · 10 files+94 added−103 removed
This commit

State

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

Diff stats

10 files+94 added−103 removed

  • tests:+39 added−5 removed
  • other:+55 added−98 removed

10 files+94 added−103 removed

modified:httpcore/adapters/redirects.py+8 added-16 removed
1import typing2from urllib.parse import urljoin, urlparse23from ..config import DEFAULT_MAX_REDIRECTS4from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects5from ..interfaces import Adapter6from ..models import URL, Headers, Request, Response7from ..status_codes import codes9from ..utils import requote_uri8910class RedirectAdapter(Adapter):11 def __init__(self, dispatch: Adapter, max_redirects: int = DEFAULT_MAX_REDIRECTS):
83 unmodified lines
95 Return the URL for the redirect to follow.96 """97 location = response.headers["Location"]98101 # Handle redirection without scheme (see: RFC 1808 Section 4)102 if location.startswith("//"):103 location = f"{request.url.scheme}:{location}"99 url = URL(location, allow_relative=True)100105 # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)106 parsed = urlparse(location)107 if parsed.fragment == "" and request.url.fragment:108 parsed = parsed._replace(fragment=request.url.fragment)109 url = parsed.geturl()110101 # Facilitate relative 'location' headers, as allowed by RFC 7231.102 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')103 # Compliant with RFC3986, we percent encode the url.114 if not parsed.netloc:115 url = urljoin(str(request.url), requote_uri(url))116 else:117 url = requote_uri(url)104 if not url.is_absolute:105 url = url.resolve_with(request.url.copy_with(fragment=None))106119 return URL(url)107 # Attach previous fragment if needed (RFC 7231 7.1.2)108 if request.url.fragment and not url.fragment:109 url = url.copy_with(fragment=request.url.fragment)110111 return url112113 def redirect_headers(self, request: Request, url: URL) -> Headers:114 """115 Strip Authorization headers when responses are redirected away from116 the origin.
15 unmodified lines
modified:httpcore/dispatch/connection.py+2 added-2 removed
55 unmodified lines
56 timeout = options.get("timeout", self.timeout)57 assert isinstance(ssl, SSLConfig)58 assert isinstance(timeout, TimeoutConfig)5960 hostname = self.origin.hostname60 host = self.origin.host61 port = self.origin.port62 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None6364 if self.release_func is None:65 on_release = None66 else:67 on_release = functools.partial(self.release_func, self)6869 reader, writer, protocol = await connect(hostname, port, ssl_context, timeout)69 reader, writer, protocol = await connect(host, port, ssl_context, timeout)70 if protocol == Protocol.HTTP_2:71 self.h2_connection = HTTP2Connection(reader, writer, on_release=on_release)72 else:73 self.h11_connection = HTTP11Connection(
20 unmodified lines
modified:httpcore/dispatch/http2.py+1 added-1 removed
97 unmodified lines
98 async def send_headers(self, request: Request, timeout: OptionalTimeout) -> int:99 stream_id = self.h2_state.get_next_available_stream_id()100 headers = [101 (b":method", request.method.encode()),102 (b":authority", request.url.hostname.encode()),102 (b":authority", request.url.host.encode()),103 (b":scheme", request.url.scheme.encode()),104 (b":path", request.url.full_path.encode()),105 ] + request.headers.raw106 self.h2_state.send_headers(stream_id, headers)
50 unmodified lines
modified:httpcore/__init__.py+1 added
6 unmodified lines
7from .dispatch.http11 import HTTP11Connection8from .exceptions import (9 ConnectTimeout,10 DecodingError,11 InvalidURL,12 PoolTimeout,13 ProtocolError,14 ReadTimeout,15 RedirectBodyUnavailable,
14 unmodified lines
modified:httpcore/models.py+41 added-26 removed
1import cgi2import typing3from urllib.parse import urlsplit34import chardet5import rfc398667from .config import SSLConfig, TimeoutConfig8from .decoders import (9 ACCEPT_ENCODING,
1 unmodified line
11 Decoder,12 IdentityDecoder,13 MultiDecoder,14)15from .exceptions import ResponseClosed, ResponseNotRead, StreamConsumed15from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed16from .status_codes import codes17from .utils import (18 get_reason_phrase,19 is_known_encoding,
12 unmodified lines
32ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]333435class URL:36 def __init__(self, url: URLTypes) -> None:36 def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:37 if isinstance(url, str):38 self.components = urlsplit(url)38 self.components = rfc3986.api.uri_reference(url).normalize()39 elif isinstance(url, rfc3986.uri.URIReference):40 self.components = url41 else:42 self.components = url.components4344 if not allow_relative:42 if not self.components.scheme:43 raise ValueError("No scheme included in URL.")44 if self.components.scheme not in ("http", "https"):45 raise ValueError('URL scheme must be "http" or "https".')46 if not self.components.hostname:47 raise ValueError("No hostname included in URL.")45 if not self.scheme:46 raise InvalidURL("No scheme included in URL.")47 if self.scheme not in ("http", "https"):48 raise InvalidURL('URL scheme must be "http" or "https".')49 if not self.host:50 raise InvalidURL("No hostname included in URL.")5152 @property53 def scheme(self) -> str:51 return self.components.scheme54 return self.components.scheme or ""5556 @property54 def netloc(self) -> str:55 return self.components.netloc57 def authority(self) -> str:58 return self.components.authority or ""5960 @property61 def path(self) -> str:59 return self.components.path62 return self.components.path or "/"6364 @property65 def query(self) -> str:63 return self.components.query66 return self.components.query or ""6768 @property69 def fragment(self) -> str:67 return self.components.fragment70 return self.components.fragment or ""7172 @property70 def hostname(self) -> str:71 return self.components.hostname73 def host(self) -> str:74 return self.components.host or ""7576 @property77 def port(self) -> int:78 port = self.components.port
13 unmodified lines
92 def is_secure(self) -> bool:93 return self.components.scheme == "https"9495 @property96 def is_absolute(self) -> bool:97 return self.components.is_absolute()9899 @property100 def origin(self) -> "Origin":101 return Origin(self)102103 def copy_with(self, **kwargs: typing.Any) -> "URL":104 return URL(self.components.copy_with(**kwargs))105106 def resolve_with(self, base_url: URLTypes) -> "URL":107 if isinstance(base_url, URL):108 base_url = base_url.components109 return URL(self.components.resolve_with(base_url))110111 def __hash__(self) -> int:112 return hash(str(self))113114 def __eq__(self, other: typing.Any) -> bool:115 return isinstance(other, URL) and str(self) == str(other)116117 def __str__(self) -> str:103 return self.components.geturl()118 return self.components.unsplit()119120 def __repr__(self) -> str:121 class_name = self.__class__.__name__122 url_str = str(self)123 return f"{class_name}({url_str!r})"124125126class Origin:112 def __init__(self, url: typing.Union[str, URL]) -> None:113 if isinstance(url, str):127 def __init__(self, url: URLTypes) -> None:128 if not isinstance(url, URL):129 url = URL(url)130 self.is_ssl = url.scheme == "https"116 self.hostname = url.hostname.lower()131 self.host = url.host132 self.port = url.port133134 def __eq__(self, other: typing.Any) -> bool:135 return (136 isinstance(other, self.__class__)137 and self.is_ssl == other.is_ssl123 and self.hostname == other.hostname138 and self.host == other.host139 and self.port == other.port140 )141142 def __hash__(self) -> int:128 return hash((self.is_ssl, self.hostname, self.port))143 return hash((self.is_ssl, self.host, self.port))144145146class Headers(typing.MutableMapping[str, str]):147 """
231 unmodified lines
379 "content-length" in self.headers or "transfer-encoding" in self.headers380 )381 has_accept_encoding = "accept-encoding" in self.headers382368 if not has_host:369 auto_headers.append((b"host", self.url.netloc.encode("ascii")))383 if not has_host and self.url.authority:384 auto_headers.append((b"host", self.url.authority.encode("ascii")))385 if not has_content_length:386 if self.is_streaming:387 auto_headers.append((b"transfer-encoding", b"chunked"))388 elif self.content:
192 unmodified lines
modified:httpcore/utils.py-52 removed
1import codecs2import http3import typing4from urllib.parse import quote46from .exceptions import InvalidURL58# The unreserved URI characters (RFC 3986)9UNRESERVED_SET = frozenset(10 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"11)121314def unquote_unreserved(uri: str) -> str:15 """16 Un-escape any percent-escape sequences in a URI that are unreserved17 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.18 """19 parts = uri.split("%")20 for i in range(1, len(parts)):21 h = parts[i][0:2]22 if len(h) == 2 and h.isalnum():23 try:24 c = chr(int(h, 16))25 except ValueError:26 raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)2728 if c in UNRESERVED_SET:29 parts[i] = c + parts[i][2:]30 else:31 parts[i] = "%" + parts[i]32 else:33 parts[i] = "%" + parts[i]34 return "".join(parts)353637def requote_uri(uri: str) -> str:38 """39 Re-quote the given URI.4041 This function passes the given URI through an unquote/quote cycle to42 ensure that it is fully and consistently quoted.43 """44 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"45 safe_without_percent = "!#$&'()*+,/:;=?@[]~"46 try:47 # Unquote only the unreserved characters48 # Then quote only illegal characters (do not quote reserved,49 # unreserved, or '%')50 return quote(unquote_unreserved(uri), safe=safe_with_percent)51 except InvalidURL:52 # We couldn't unquote the given URI, so let's try quoting it, but53 # there may be unquoted '%'s in the URI. We need to make sure they're54 # properly quoted so they do not cause issues elsewhere.55 return quote(uri, safe=safe_without_percent)56576def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:7 """8 Coerce str/bytes into a strictly byte-wise HTTP header key.9 """
30 unmodified lines
modified:tests/models/test_requests.py+3 added-3 removed
91 unmodified lines
92 assert request.url.full_path == "/abc?foo=bar"939495def test_invalid_urls():96 with pytest.raises(ValueError):96 with pytest.raises(httpcore.InvalidURL):97 httpcore.Request("GET", "example.org")9899 with pytest.raises(ValueError):99 with pytest.raises(httpcore.InvalidURL):100 httpcore.Request("GET", "invalid://example.org")101102 with pytest.raises(ValueError):102 with pytest.raises(httpcore.InvalidURL):103 httpcore.Request("GET", "http:///foo")
modified:tests/models/test_responses.py+36 added-2 removed
35 unmodified lines
36 assert response.encoding == "utf-8"373839def test_response_set_explicit_encoding():40 headers = {"Content-Type": "text-plain; charset=utf-8"} # Deliberately incorrect charset40 headers = {41 "Content-Type": "text-plain; charset=utf-8"42 } # Deliberately incorrect charset43 response = httpcore.Response(44 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers45 )44 response.encoding = 'latin-1'46 response.encoding = "latin-1"47 assert response.text == "Latin 1: ÿ"48 assert response.encoding == "latin-1"4950
22 unmodified lines
73 assert response.is_closed747576@pytest.mark.asyncio77async def test_raw_interface():78 response = httpcore.Response(200, content=b"Hello, world!")7980 raw = b""81 async for part in response.raw():82 raw += part83 assert raw == b"Hello, world!"848586@pytest.mark.asyncio87async def test_stream_interface():88 response = httpcore.Response(200, content=b"Hello, world!")8990 content = b""91 async for part in response.stream():92 content += part93 assert content == b"Hello, world!"949596@pytest.mark.asyncio97async def test_stream_interface_after_read():98 response = httpcore.Response(200, content=b"Hello, world!")99100 await response.read()101102 content = b""103 async for part in response.stream():104 content += part105 assert content == b"Hello, world!"106107108@pytest.mark.asyncio109async def test_streaming_response():110 response = httpcore.Response(200, content=streaming_body())111112 assert response.status_code == 200
36 unmodified lines
modified:requirements.txt+1 added
1certifi2chardet3h114h25rfc398667# Optional8brotlipy9
10 unmodified lines
modified:setup.py+1 added-1 removed
45 unmodified lines
46 author="Tom Christie",47 author_email="tom@tomchristie.com",48 packages=get_packages("httpcore"),49 data_files=[("", ["LICENSE.md"])],50 install_requires=["h11", "h2", "certifi", "chardet"],50 install_requires=["h11", "h2", "certifi", "chardet", "rfc3986"],51 classifiers=[52 "Development Status :: 3 - Alpha",53 "Environment :: Web Environment",54 "Intended Audience :: Developers",
9 unmodified lines