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
Provenance
- Commit
302fe93- Tree
df8b9b0- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
fd9823e
10 files changed+94 added−103 removed
modified:httpcore/adapters/redirects.py+8 added-16 removed
1 import typing2-from urllib.parse import urljoin, urlparse2 3 from ..config import DEFAULT_MAX_REDIRECTS4 from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects5 from ..interfaces import Adapter6 from ..models import URL, Headers, Request, Response7 from ..status_codes import codes9-from ..utils import requote_uri8 9 10 class RedirectAdapter(Adapter):11 def __init__(self, dispatch: Adapter, max_redirects: int = DEFAULT_MAX_REDIRECTS):83 unmodified lines95 Return the URL for the redirect to follow.96 """97 location = response.headers["Location"]98 101- # 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)100 105- # 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()110-101 # 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))106 119- 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)110 111+ return url112+113 def redirect_headers(self, request: Request, url: URL) -> Headers:114 """115 Strip Authorization headers when responses are redirected away from116 the origin.15 unmodified linesmodified:httpcore/dispatch/connection.py+2 added-2 removed
55 unmodified lines56 timeout = options.get("timeout", self.timeout)57 assert isinstance(ssl, SSLConfig)58 assert isinstance(timeout, TimeoutConfig)59 60- 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 None63 64 if self.release_func is None:65 on_release = None66 else:67 on_release = functools.partial(self.release_func, self)68 69- 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 linesmodified:httpcore/dispatch/http2.py+1 added-1 removed
97 unmodified lines98 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 linesmodified:httpcore/__init__.py+1 added
6 unmodified lines7 from .dispatch.http11 import HTTP11Connection8 from .exceptions import (9 ConnectTimeout,10 DecodingError,11+ InvalidURL,12 PoolTimeout,13 ProtocolError,14 ReadTimeout,15 RedirectBodyUnavailable,14 unmodified linesmodified:httpcore/models.py+41 added-26 removed
1 import cgi2 import typing3-from urllib.parse import urlsplit3 4 import chardet5+import rfc39866 7 from .config import SSLConfig, TimeoutConfig8 from .decoders import (9 ACCEPT_ENCODING,1 unmodified line11 Decoder,12 IdentityDecoder,13 MultiDecoder,14 )15-from .exceptions import ResponseClosed, ResponseNotRead, StreamConsumed15+from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed16 from .status_codes import codes17 from .utils import (18 get_reason_phrase,19 is_known_encoding,12 unmodified lines32 ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]33 34 35 class 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.components43 44+ 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.")51 52 @property53 def scheme(self) -> str:51- return self.components.scheme54+ return self.components.scheme or ""55 56 @property54- def netloc(self) -> str:55- return self.components.netloc57+ def authority(self) -> str:58+ return self.components.authority or ""59 60 @property61 def path(self) -> str:59- return self.components.path62+ return self.components.path or "/"63 64 @property65 def query(self) -> str:63- return self.components.query66+ return self.components.query or ""67 68 @property69 def fragment(self) -> str:67- return self.components.fragment70+ return self.components.fragment or ""71 72 @property70- def hostname(self) -> str:71- return self.components.hostname73+ def host(self) -> str:74+ return self.components.host or ""75 76 @property77 def port(self) -> int:78 port = self.components.port13 unmodified lines92 def is_secure(self) -> bool:93 return self.components.scheme == "https"94 95 @property96+ def is_absolute(self) -> bool:97+ return self.components.is_absolute()98+99+ @property100 def origin(self) -> "Origin":101 return Origin(self)102 103+ def copy_with(self, **kwargs: typing.Any) -> "URL":104+ return URL(self.components.copy_with(**kwargs))105+106+ 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))110+111 def __hash__(self) -> int:112 return hash(str(self))113 114 def __eq__(self, other: typing.Any) -> bool:115 return isinstance(other, URL) and str(self) == str(other)116 117 def __str__(self) -> str:103- return self.components.geturl()118+ return self.components.unsplit()119 120 def __repr__(self) -> str:121 class_name = self.__class__.__name__122 url_str = str(self)123 return f"{class_name}({url_str!r})"124 125 126 class 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.port133 134 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 )141 142 def __hash__(self) -> int:128- return hash((self.is_ssl, self.hostname, self.port))143+ return hash((self.is_ssl, self.host, self.port))144 145 146 class Headers(typing.MutableMapping[str, str]):147 """231 unmodified lines379 "content-length" in self.headers or "transfer-encoding" in self.headers380 )381 has_accept_encoding = "accept-encoding" in self.headers382 368- 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 linesmodified:httpcore/utils.py-52 removed
1 import codecs2 import http3 import typing4-from urllib.parse import quote4 6-from .exceptions import InvalidURL5 8-# The unreserved URI characters (RFC 3986)9-UNRESERVED_SET = frozenset(10- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"11-)12-13-14-def 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)27-28- 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)35-36-37-def requote_uri(uri: str) -> str:38- """39- Re-quote the given URI.40-41- 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)56-57-6 def 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 linesmodified:tests/models/test_requests.py+3 added-3 removed
91 unmodified lines92 assert request.url.full_path == "/abc?foo=bar"93 94 95 def test_invalid_urls():96- with pytest.raises(ValueError):96+ with pytest.raises(httpcore.InvalidURL):97 httpcore.Request("GET", "example.org")98 99- with pytest.raises(ValueError):99+ with pytest.raises(httpcore.InvalidURL):100 httpcore.Request("GET", "invalid://example.org")101 102- 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 lines36 assert response.encoding == "utf-8"37 38 39 def 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"49 50 22 unmodified lines73 assert response.is_closed74 75 76 @pytest.mark.asyncio77+async def test_raw_interface():78+ response = httpcore.Response(200, content=b"Hello, world!")79+80+ raw = b""81+ async for part in response.raw():82+ raw += part83+ assert raw == b"Hello, world!"84+85+86+@pytest.mark.asyncio87+async def test_stream_interface():88+ response = httpcore.Response(200, content=b"Hello, world!")89+90+ content = b""91+ async for part in response.stream():92+ content += part93+ assert content == b"Hello, world!"94+95+96+@pytest.mark.asyncio97+async def test_stream_interface_after_read():98+ response = httpcore.Response(200, content=b"Hello, world!")99+100+ await response.read()101+102+ content = b""103+ async for part in response.stream():104+ content += part105+ assert content == b"Hello, world!"106+107+108+@pytest.mark.asyncio109 async def test_streaming_response():110 response = httpcore.Response(200, content=streaming_body())111 112 assert response.status_code == 20036 unmodified linesmodified:requirements.txt+1 added
1 certifi2 chardet3 h114 h25+rfc39866 7 # Optional8 brotlipy9 10 unmodified linesmodified:setup.py+1 added-1 removed
45 unmodified lines46 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