Skip to content
Myr

Drop `rfc3986` requirement. (#2252)

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

* Drop RawURL * First pass at adding urlparse * Update urlparse * Add urlparse * Add urlparse * Unicode non-printables can be valid in IDNA hostnames * Update _urlparse.py docstring * Linting * Trim away ununsed codepaths * Tweaks for path validation depending on scheme and authority presence * Minor cleanups * Minor cleanups * full_path -> raw_path, forr internal consistency * Linting fixes * Drop rfc3986 dependency * Add test for #1833 * Linting * Drop 'rfc3986' dependancy from README and docs homepage

authored by Tom Christie · committed by GitHub · parent 7c53d99 · Browse files · 8 files+762 added−257 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: Thomas Grainger <tagrain@gmail.com>

Diff stats

8 files+762 added−257 removed

  • tests:+245 added−41 removed
  • other:+517 added−216 removed

8 files+762 added−257 removed

modified:docs/index.md+1 added-2 removed
added:httpx/_urlparse.py+435 added
1"""2An implementation of `urlparse` that provides URL validation and normalization3as described by RFC3986.45We rely on this implementation rather than the one in Python's stdlib, because:67* It provides more complete URL validation.8* It properly differentiates between an empty querystring and an absent querystring,9 to distinguish URLs with a trailing '?'.10* It handles scheme, hostname, port, and path normalization.11* It supports IDNA hostnames, normalizing them to their encoded form.12* The API supports passing individual components, as well as the complete URL string.1314Previously we relied on the excellent `rfc3986` package to handle URL parsing and15validation, but this module provides a simpler alternative, with less indirection16required.17"""18import ipaddress19import re20import typing2122import idna2324from ._exceptions import InvalidURL2526MAX_URL_LENGTH = 655362728# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.329UNRESERVED_CHARACTERS = (30 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"31)32SUB_DELIMS = "!$&'()*+,;="3334PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}")353637# {scheme}: (optional)38# //{authority} (optional)39# {path}40# ?{query} (optional)41# #{fragment} (optional)42URL_REGEX = re.compile(43 (44 r"(?:(?P<scheme>{scheme}):)?"45 r"(?://(?P<authority>{authority}))?"46 r"(?P<path>{path})"47 r"(?:\?(?P<query>{query}))?"48 r"(?:#(?P<fragment>{fragment}))?"49 ).format(50 scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?",51 authority="[^/?#]*",52 path="[^?#]*",53 query="[^#]*",54 fragment=".*",55 )56)5758# {userinfo}@ (optional)59# {host}60# :{port} (optional)61AUTHORITY_REGEX = re.compile(62 (63 r"(?:(?P<userinfo>{userinfo})@)?" r"(?P<host>{host})" r":?(?P<port>{port})?"64 ).format(65 userinfo="[^@]*", # Any character sequence not including '@'.66 host="(\\[.*\\]|[^:]*)", # Either any character sequence not including ':',67 # or an IPv6 address enclosed within square brackets.68 port=".*", # Any character sequence.69 )70)717273# If we call urlparse with an individual component, then we need to regex74# validate that component individually.75# Note that we're duplicating the same strings as above. Shock! Horror!!76COMPONENT_REGEX = {77 "scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"),78 "authority": re.compile("[^/?#]*"),79 "path": re.compile("[^?#]*"),80 "query": re.compile("[^#]*"),81 "fragment": re.compile(".*"),82 "userinfo": re.compile("[^@]*"),83 "host": re.compile("(\\[.*\\]|[^:]*)"),84 "port": re.compile(".*"),85}868788# We use these simple regexs as a first pass before handing off to89# the stdlib 'ipaddress' module for IP address validation.90IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+.[0-9]+.[0-9]+.[0-9]+$")91IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$")929394class ParseResult(typing.NamedTuple):95 scheme: str96 userinfo: str97 host: str98 port: typing.Optional[int]99 path: str100 query: typing.Optional[str]101 fragment: typing.Optional[str]102103 @property104 def authority(self) -> str:105 return "".join(106 [107 f"{self.userinfo}@" if self.userinfo else "",108 f"[{self.host}]" if ":" in self.host else self.host,109 f":{self.port}" if self.port is not None else "",110 ]111 )112113 @property114 def netloc(self) -> str:115 return "".join(116 [117 f"[{self.host}]" if ":" in self.host else self.host,118 f":{self.port}" if self.port is not None else "",119 ]120 )121122 def copy_with(self, **kwargs: typing.Optional[str]) -> "ParseResult":123 if not kwargs:124 return self125126 defaults = {127 "scheme": self.scheme,128 "authority": self.authority,129 "path": self.path,130 "query": self.query,131 "fragment": self.fragment,132 }133 defaults.update(kwargs)134 return urlparse("", **defaults)135136 def __str__(self) -> str:137 authority = self.authority138 return "".join(139 [140 f"{self.scheme}:" if self.scheme else "",141 f"//{authority}" if authority else "",142 self.path,143 f"?{self.query}" if self.query is not None else "",144 f"#{self.fragment}" if self.fragment is not None else "",145 ]146 )147148149def urlparse(url: str = "", **kwargs: typing.Optional[str]) -> ParseResult:150 # Initial basic checks on allowable URLs.151 # ---------------------------------------152153 # Hard limit the maximum allowable URL length.154 if len(url) > MAX_URL_LENGTH:155 raise InvalidURL("URL too long")156157 # If a URL includes any ASCII control characters including \t, \r, \n,158 # then treat it as invalid.159 if any(char.isascii() and not char.isprintable() for char in url):160 raise InvalidURL("Invalid non-printable ASCII character in URL")161162 # Some keyword arguments require special handling.163 # ------------------------------------------------164165 # Coerce "port" to a string, if it is provided as an integer.166 if "port" in kwargs:167 port = kwargs["port"]168 kwargs["port"] = str(port) if isinstance(port, int) else port169170 # Replace "netloc" with "host and "port".171 if "netloc" in kwargs:172 netloc = kwargs.pop("netloc") or ""173 kwargs["host"], _, kwargs["port"] = netloc.partition(":")174175 # Replace "username" and/or "password" with "userinfo".176 if "username" in kwargs or "password" in kwargs:177 username = quote(kwargs.pop("username", "") or "")178 password = quote(kwargs.pop("password", "") or "")179 kwargs["userinfo"] = f"{username}:{password}" if password else username180181 # Replace "raw_path" with "path" and "query".182 if "raw_path" in kwargs:183 raw_path = kwargs.pop("raw_path") or ""184 kwargs["path"], seperator, kwargs["query"] = raw_path.partition("?")185 if not seperator:186 kwargs["query"] = None187188 # Ensure that IPv6 "host" addresses are always escaped with "[...]".189 if "host" in kwargs:190 host = kwargs.get("host") or ""191 if ":" in host and not (host.startswith("[") and host.endswith("]")):192 kwargs["host"] = f"[{host}]"193194 # If any keyword arguments are provided, ensure they are valid.195 # -------------------------------------------------------------196197 for key, value in kwargs.items():198 if key not in (199 "scheme",200 "authority",201 "path",202 "query",203 "fragment",204 "userinfo",205 "host",206 "port",207 ):208 raise TypeError(f"'{key}' is an invalid keyword argument for urlparse()")209210 if value is not None:211 if len(value) > MAX_URL_LENGTH:212 raise InvalidURL(f"URL component '{key}' too long")213214 # If a component includes any ASCII control characters including \t, \r, \n,215 # then treat it as invalid.216 if any(char.isascii() and not char.isprintable() for char in value):217 raise InvalidURL(218 f"Invalid non-printable ASCII character in URL component '{key}'"219 )220221 # Ensure that keyword arguments match as a valid regex.222 if not COMPONENT_REGEX[key].fullmatch(value):223 raise InvalidURL(f"Invalid URL component '{key}'")224225 # The URL_REGEX will always match, but may have empty components.226 url_match = URL_REGEX.match(url)227 assert url_match is not None228 url_dict = url_match.groupdict()229230 # * 'scheme', 'authority', and 'path' may be empty strings.231 # * 'query' may be 'None', indicating no trailing "?" portion.232 # Any string including the empty string, indicates a trailing "?".233 # * 'fragment' may be 'None', indicating no trailing "#" portion.234 # Any string including the empty string, indicates a trailing "#".235 scheme = kwargs.get("scheme", url_dict["scheme"]) or ""236 authority = kwargs.get("authority", url_dict["authority"]) or ""237 path = kwargs.get("path", url_dict["path"]) or ""238 query = kwargs.get("query", url_dict["query"])239 fragment = kwargs.get("fragment", url_dict["fragment"])240241 # The AUTHORITY_REGEX will always match, but may have empty components.242 authority_match = AUTHORITY_REGEX.match(authority)243 assert authority_match is not None244 authority_dict = authority_match.groupdict()245246 # * 'userinfo' and 'host' may be empty strings.247 # * 'port' may be 'None'.248 userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or ""249 host = kwargs.get("host", authority_dict["host"]) or ""250 port = kwargs.get("port", authority_dict["port"])251252 # Normalize and validate each component.253 # We end up with a parsed representation of the URL,254 # with components that are plain ASCII bytestrings.255 parsed_scheme: str = scheme.lower()256 parsed_userinfo: str = quote(userinfo, safe=SUB_DELIMS + ":")257 parsed_host: str = encode_host(host)258 parsed_port: typing.Optional[int] = normalize_port(port, scheme)259260 has_scheme = parsed_scheme != ""261 has_authority = (262 parsed_userinfo != "" or parsed_host != "" or parsed_port is not None263 )264 validate_path(path, has_scheme=has_scheme, has_authority=has_authority)265 if has_authority:266 path = normalize_path(path)267268 parsed_path: str = quote(path, safe=SUB_DELIMS + ":@/")269 parsed_query: typing.Optional[str] = (270 None if query is None else quote(query, safe=SUB_DELIMS + "/?")271 )272 parsed_fragment: typing.Optional[str] = (273 None if fragment is None else quote(fragment, safe=SUB_DELIMS + "/?")274 )275276 # The parsed ASCII bytestrings are our canonical form.277 # All properties of the URL are derived from these.278 return ParseResult(279 parsed_scheme,280 parsed_userinfo,281 parsed_host,282 parsed_port,283 parsed_path,284 parsed_query,285 parsed_fragment,286 )287288289def encode_host(host: str) -> str:290 if not host:291 return ""292293 elif IPv4_STYLE_HOSTNAME.match(host):294 # Validate IPv4 hostnames like #.#.#.#295 #296 # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2297 #298 # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet299 try:300 ipaddress.IPv4Address(host)301 except ipaddress.AddressValueError:302 raise InvalidURL("Invalid IPv4 address")303 return host304305 elif IPv6_STYLE_HOSTNAME.match(host):306 # Validate IPv6 hostnames like [...]307 #308 # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2309 #310 # "A host identified by an Internet Protocol literal address, version 6311 # [RFC3513] or later, is distinguished by enclosing the IP literal312 # within square brackets ("[" and "]"). This is the only place where313 # square bracket characters are allowed in the URI syntax."314 try:315 ipaddress.IPv6Address(host[1:-1])316 except ipaddress.AddressValueError:317 raise InvalidURL("Invalid IPv6 address")318 return host[1:-1]319320 elif host.isascii():321 # Regular ASCII hostnames322 #323 # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2324 #325 # reg-name = *( unreserved / pct-encoded / sub-delims )326 return quote(host.lower(), safe=SUB_DELIMS)327328 # IDNA hostnames329 try:330 return idna.encode(host.lower()).decode("ascii")331 except idna.IDNAError:332 raise InvalidURL("Invalid IDNA hostname")333334335def normalize_port(336 port: typing.Optional[typing.Union[str, int]], scheme: str337) -> typing.Optional[int]:338 # From https://tools.ietf.org/html/rfc3986#section-3.2.3339 #340 # "A scheme may define a default port. For example, the "http" scheme341 # defines a default port of "80", corresponding to its reserved TCP342 # port number. The type of port designated by the port number (e.g.,343 # TCP, UDP, SCTP) is defined by the URI scheme. URI producers and344 # normalizers should omit the port component and its ":" delimiter if345 # port is empty or if its value would be the same as that of the346 # scheme's default."347 if port is None or port == "":348 return None349350 try:351 port_as_int = int(port)352 except ValueError:353 raise InvalidURL("Invalid port")354355 # See https://url.spec.whatwg.org/#url-miscellaneous356 default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get(357 scheme358 )359 if port_as_int == default_port:360 return None361 return port_as_int362363364def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None:365 """366 Path validation rules that depend on if the URL contains a scheme or authority component.367368 See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3369 """370 if has_authority:371 # > If a URI contains an authority component, then the path component372 # > must either be empty or begin with a slash ("/") character."373 if path and not path.startswith("/"):374 raise InvalidURL("For absolute URLs, path must be empty or begin with '/'")375 else:376 # > If a URI does not contain an authority component, then the path cannot begin377 # > with two slash characters ("//").378 if path.startswith("//"):379 raise InvalidURL(380 "URLs with no authority component cannot have a path starting with '//'"381 )382 # > In addition, a URI reference (Section 4.1) may be a relative-path reference, in which383 # > case the first path segment cannot contain a colon (":") character.384 if path.startswith(":") and not has_scheme:385 raise InvalidURL(386 "URLs with no scheme component cannot have a path starting with ':'"387 )388389390def normalize_path(path: str) -> str:391 """392 Drop "." and ".." segments from a URL path.393394 For example:395396 normalize_path("/path/./to/somewhere/..") == "/path/to"397 """398 # https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4399 components = path.split("/")400 output: typing.List[str] = []401 for component in components:402 if component == ".":403 pass404 elif component == "..":405 if output and output != [""]:406 output.pop()407 else:408 output.append(component)409 return "/".join(output)410411412def percent_encode(char: str) -> str:413 """414 Replace every character in a string with the percent-encoded representation.415416 Characters outside the ASCII range are represented with their a percent-encoded417 representation of their UTF-8 byte sequence.418419 For example:420421 percent_encode(" ") == "%20"422 """423 return "".join([f"%{byte:02x}" for byte in char.encode("utf-8")]).upper()424425426def quote(string: str, safe: str = "/") -> str:427 NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe428 if string.count("%") == len(PERCENT_ENCODED_REGEX.findall(string)):429 # If all occurances of '%' are valid '%xx' escapes, then treat430 # percent as a non-escaping character.431 NON_ESCAPED_CHARS += "%"432433 return "".join(434 [char if char in NON_ESCAPED_CHARS else percent_encode(char) for char in string]435 )
modified:httpx/_urls.py+79 added-211 removed
1import typing2from urllib.parse import parse_qs, quote, unquote, urlencode2from urllib.parse import parse_qs, unquote, urlencode34import idna5import rfc39866import rfc3986.exceptions58from ._exceptions import InvalidURL6from ._types import PrimitiveData, QueryParamTypes, RawURL, URLTypes7from ._urlparse import urlparse8from ._utils import primitive_value_to_str91011class URL:
55 unmodified lines
67 * `url.query` is raw bytes, without URL escaping. A URL query string portion can only68 be properly URL escaped when decoding the parameter names and values themselves.69 """7073 _uri_reference: rfc3986.URIReference7471 def __init__(72 self, url: typing.Union["URL", str] = "", **kwargs: typing.Any73 ) -> None:78 if isinstance(url, str):79 try:80 self._uri_reference = rfc3986.iri_reference(url).encode()81 except rfc3986.exceptions.InvalidAuthority as exc:82 raise InvalidURL(message=str(exc)) from None74 if kwargs:75 allowed = {76 "scheme": str,77 "username": str,78 "password": str,79 "userinfo": bytes,80 "host": str,81 "port": int,82 "netloc": bytes,83 "path": str,84 "query": bytes,85 "raw_path": bytes,86 "fragment": str,87 "params": object,88 }8984 if self.is_absolute_url:85 # We don't want to normalize relative URLs, since doing so86 # removes any leading `../` portion.87 self._uri_reference = self._uri_reference.normalize()90 # Perform type checking for all supported keyword arguments.91 for key, value in kwargs.items():92 if key not in allowed:93 message = f"{key!r} is an invalid keyword argument for URL()"94 raise TypeError(message)95 if value is not None and not isinstance(value, allowed[key]):96 expected = allowed[key].__name__97 seen = type(value).__name__98 message = f"Argument {key!r} must be {expected} but got {seen}"99 raise TypeError(message)100 if isinstance(value, bytes):101 kwargs[key] = value.decode("ascii")102103 if "params" in kwargs:104 # Replace any "params" keyword with the raw "query" instead.105 #106 # Ensure that empty params use `kwargs["query"] = None` rather107 # than `kwargs["query"] = ""`, so that generated URLs do not108 # include an empty trailing "?".109 params = kwargs.pop("params")110 kwargs["query"] = None if not params else str(QueryParams(params))111112 if isinstance(url, str):113 self._uri_reference = urlparse(url, **kwargs)114 elif isinstance(url, URL):89 self._uri_reference = url._uri_reference115 self._uri_reference = url._uri_reference.copy_with(**kwargs)116 else:117 raise TypeError(118 f"Invalid type for url. Expected str or httpx.URL, got {type(url)}: {url!r}"119 )12095 # Perform port normalization, following the WHATWG spec for default ports.96 #97 # See:98 # * https://tools.ietf.org/html/rfc3986#section-3.2.399 # * https://url.spec.whatwg.org/#url-miscellaneous100 # * https://url.spec.whatwg.org/#scheme-state101 default_port = {102 "ftp": ":21",103 "http": ":80",104 "https": ":443",105 "ws": ":80",106 "wss": ":443",107 }.get(self._uri_reference.scheme, "")108 authority = self._uri_reference.authority or ""109 if default_port and authority.endswith(default_port):110 authority = authority[: -len(default_port)]111 self._uri_reference = self._uri_reference.copy_with(authority=authority)112113 if kwargs:114 self._uri_reference = self.copy_with(**kwargs)._uri_reference115121 @property122 def scheme(self) -> str:123 """124 The URL scheme, such as "http", "https".125 Always normalised to lowercase.126 """122 return self._uri_reference.scheme or ""127 return self._uri_reference.scheme128129 @property130 def raw_scheme(self) -> bytes:131 """132 The raw bytes representation of the URL scheme, such as b"http", b"https".133 Always normalised to lowercase.134 """130 return self.scheme.encode("ascii")135 return self._uri_reference.scheme.encode("ascii")136137 @property138 def userinfo(self) -> bytes:139 """140 The URL userinfo as a raw bytestring.141 For example: b"jo%40email.com:a%20secret".142 """138 userinfo = self._uri_reference.userinfo or ""139 return userinfo.encode("ascii")143 return self._uri_reference.userinfo.encode("ascii")144145 @property146 def username(self) -> str:147 """148 The URL username as a string, with URL decoding applied.149 For example: "jo@email.com"150 """147 userinfo = self._uri_reference.userinfo or ""151 userinfo = self._uri_reference.userinfo152 return unquote(userinfo.partition(":")[0])153154 @property155 def password(self) -> str:156 """157 The URL password as a string, with URL decoding applied.158 For example: "a secret"159 """156 userinfo = self._uri_reference.userinfo or ""160 userinfo = self._uri_reference.userinfo161 return unquote(userinfo.partition(":")[2])162163 @property164 def host(self) -> str:
14 unmodified lines
179180 url = httpx.URL("https://[::ffff:192.168.0.1]")181 assert url.host == "::ffff:192.168.0.1"182 """179 host: str = self._uri_reference.host or ""183 host: str = self._uri_reference.host184181 if host and ":" in host and host[0] == "[":182 # it's an IPv6 address183 host = host.lstrip("[").rstrip("]")184185 if host.startswith("xn--"):186 host = idna.decode(host)187188 return host
17 unmodified lines
206207 url = httpx.URL("https://[::ffff:192.168.0.1]")208 assert url.raw_host == b"::ffff:192.168.0.1"209 """210 host: str = self._uri_reference.host or ""210 return self._uri_reference.host.encode("ascii")211212 if host and ":" in host and host[0] == "[":213 # it's an IPv6 address214 host = host.lstrip("[").rstrip("]")215216 return host.encode("ascii")217212 @property213 def port(self) -> typing.Optional[int]:214 """215 The URL port as an integer.
6 unmodified lines
222223 assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80")224 assert httpx.URL("http://www.example.com:80").port is None225 """232 port = self._uri_reference.port233 return int(port) if port else None226 return self._uri_reference.port227228 @property229 def netloc(self) -> bytes:230 """
2 unmodified lines
233234 This property may be used for generating the value of a request235 "Host" header.236 """244 host = self._uri_reference.host or ""245 port = self._uri_reference.port246 netloc = host.encode("ascii")247 if port:248 netloc = netloc + b":" + port.encode("ascii")249 return netloc237 return self._uri_reference.netloc.encode("ascii")238239 @property240 def path(self) -> str:241 """
102 unmodified lines
344345 url = httpx.URL("https://www.example.com").copy_with(username="jo@gmail.com", password="a secret")346 assert url == "https://jo%40email.com:a%20secret@www.example.com"347 """360 allowed = {361 "scheme": str,362 "username": str,363 "password": str,364 "userinfo": bytes,365 "host": str,366 "port": int,367 "netloc": bytes,368 "path": str,369 "query": bytes,370 "raw_path": bytes,371 "fragment": str,372 "params": object,373 }348 return URL(self, **kwargs)349375 # Step 1376 # ======377 #378 # Perform type checking for all supported keyword arguments.379 for key, value in kwargs.items():380 if key not in allowed:381 message = f"{key!r} is an invalid keyword argument for copy_with()"382 raise TypeError(message)383 if value is not None and not isinstance(value, allowed[key]):384 expected = allowed[key].__name__385 seen = type(value).__name__386 message = f"Argument {key!r} must be {expected} but got {seen}"387 raise TypeError(message)388389 # Step 2390 # ======391 #392 # Consolidate "username", "password", "userinfo", "host", "port" and "netloc"393 # into a single "authority" keyword, for `rfc3986`.394 if "username" in kwargs or "password" in kwargs:395 # Consolidate "username" and "password" into "userinfo".396 username = quote(kwargs.pop("username", self.username) or "")397 password = quote(kwargs.pop("password", self.password) or "")398 userinfo = f"{username}:{password}" if password else username399 kwargs["userinfo"] = userinfo.encode("ascii")400401 if "host" in kwargs or "port" in kwargs:402 # Consolidate "host" and "port" into "netloc".403 host = kwargs.pop("host", self.host) or ""404 port = kwargs.pop("port", self.port)405406 if host and ":" in host and host[0] != "[":407 # IPv6 addresses need to be escaped within square brackets.408 host = f"[{host}]"409410 kwargs["netloc"] = (411 f"{host}:{port}".encode("ascii")412 if port is not None413 else host.encode("ascii")414 )415416 if "userinfo" in kwargs or "netloc" in kwargs:417 # Consolidate "userinfo" and "netloc" into authority.418 userinfo = (kwargs.pop("userinfo", self.userinfo) or b"").decode("ascii")419 netloc = (kwargs.pop("netloc", self.netloc) or b"").decode("ascii")420 authority = f"{userinfo}@{netloc}" if userinfo else netloc421 kwargs["authority"] = authority422423 # Step 3424 # ======425 #426 # Wrangle any "path", "query", "raw_path" and "params" keywords into427 # "query" and "path" keywords for `rfc3986`.428 if "raw_path" in kwargs:429 # If "raw_path" is included, then split it into "path" and "query" components.430 raw_path = kwargs.pop("raw_path") or b""431 path, has_query, query = raw_path.decode("ascii").partition("?")432 kwargs["path"] = path433 kwargs["query"] = query if has_query else None434435 else:436 if kwargs.get("path") is not None:437 # Ensure `kwargs["path"] = <url quoted str>` for `rfc3986`.438 kwargs["path"] = quote(kwargs["path"])439440 if kwargs.get("query") is not None:441 # Ensure `kwargs["query"] = <str>` for `rfc3986`.442 #443 # Note that `.copy_with(query=None)` and `.copy_with(query=b"")`444 # are subtly different. The `None` style will not include an empty445 # trailing "?" character.446 kwargs["query"] = kwargs["query"].decode("ascii")447448 if "params" in kwargs:449 # Replace any "params" keyword with the raw "query" instead.450 #451 # Ensure that empty params use `kwargs["query"] = None` rather452 # than `kwargs["query"] = ""`, so that generated URLs do not453 # include an empty trailing "?".454 params = kwargs.pop("params")455 kwargs["query"] = None if not params else str(QueryParams(params))456457 # Step 4458 # ======459 #460 # Ensure any fragment component is quoted.461 if kwargs.get("fragment") is not None:462 kwargs["fragment"] = quote(kwargs["fragment"])463464 # Step 5465 # ======466 #467 # At this point kwargs may include keys for "scheme", "authority", "path",468 # "query" and "fragment". Together these constitute the entire URL.469 #470 # See https://tools.ietf.org/html/rfc3986#section-3471 #472 # foo://example.com:8042/over/there?name=ferret#nose473 # \_/ \______________/\_________/ \_________/ \__/474 # | | | | |475 # scheme authority path query fragment476 new_url = URL(self)477 new_url._uri_reference = self._uri_reference.copy_with(**kwargs)478 if new_url.is_absolute_url:479 new_url._uri_reference = new_url._uri_reference.normalize()480 return URL(new_url)481350 def copy_set_param(self, key: str, value: typing.Any = None) -> "URL":351 return self.copy_with(params=self.params.set(key, value))352353 def copy_add_param(self, key: str, value: typing.Any = None) -> "URL":
14 unmodified lines
368 url = httpx.URL("https://www.example.com/test")369 url = url.join("/new/path")370 assert url == "https://www.example.com/new/path"371 """504 if self.is_relative_url:505 # Workaround to handle relative URLs, which otherwise raise506 # rfc3986.exceptions.ResolutionError when used as an argument507 # in `.resolve_with`.508 return (509 self.copy_with(scheme="http", host="example.com")510 .join(url)511 .copy_with(scheme=None, host=None)512 )372 from urllib.parse import urljoin373514 # We drop any fragment portion, because RFC 3986 strictly515 # treats URLs with a fragment portion as not being absolute URLs.516 base_uri = self._uri_reference.copy_with(fragment=None)517 relative_url = URL(url)518 return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())374 return URL(urljoin(str(self), str(URL(url))))375376 def __hash__(self) -> int:377 return hash(str(self))378379 def __eq__(self, other: typing.Any) -> bool:380 return isinstance(other, (URL, str)) and str(self) == str(URL(other))381382 def __str__(self) -> str:527 return typing.cast(str, self._uri_reference.unsplit())383 return str(self._uri_reference)384385 def __repr__(self) -> str:530 class_name = self.__class__.__name__531 url_str = str(self)532 if self._uri_reference.userinfo:533 # Mask any password component in the URL representation, to lower the534 # risk of unintended leakage, such as in debug information and logging.535 username = quote(self.username)536 url_str = (537 rfc3986.urlparse(url_str)538 .copy_with(userinfo=f"{username}:[secure]")539 .unsplit()540 )541 return f"{class_name}({url_str!r})"386 scheme, userinfo, host, port, path, query, fragment = self._uri_reference387388 if ":" in userinfo:389 # Mask any password component.390 userinfo = f'{userinfo.split(":")[0]}:[secure]'391392 authority = "".join(393 [394 f"{userinfo}@" if userinfo else "",395 f"[{host}]" if ":" in host else host,396 f":{port}" if port is not None else "",397 ]398 )399 url = "".join(400 [401 f"{self.scheme}:" if scheme else "",402 f"//{authority}" if authority else "",403 path,404 f"?{query}" if query is not None else "",405 f"#{fragment}" if fragment is not None else "",406 ]407 )408409 return f"{self.__class__.__name__}({url!r})"410411412class QueryParams(typing.Mapping[str, str]):413 """414 URL query parameters, as a multi-dict.415 """
221 unmodified lines
modified:tests/models/test_url.py+12 added-40 removed
310 unmodified lines
311def test_url_copywith_security():312 """313 Prevent unexpected changes on URL after calling copy_with (CVE-2021-41945)314 """315 url = httpx.URL("https://u:p@[invalid!]//evilHost/path?t=w#tw")316 original_scheme = url.scheme317 original_userinfo = url.userinfo318 original_netloc = url.netloc319 original_raw_path = url.raw_path320 original_query = url.query321 original_fragment = url.fragment322 url = url.copy_with()323 assert url.scheme == original_scheme324 assert url.userinfo == original_userinfo325 assert url.netloc == original_netloc326 assert url.raw_path == original_raw_path327 assert url.query == original_query328 assert url.fragment == original_fragment315 with pytest.raises(httpx.InvalidURL):316 httpx.URL("https://u:p@[invalid!]//evilHost/path?t=w#tw")317330 url = httpx.URL("https://u:p@[invalid!]//evilHost/path?t=w#tw")331 original_scheme = url.scheme332 original_netloc = url.netloc333 original_raw_path = url.raw_path334 original_query = url.query335 original_fragment = url.fragment336 url = url.copy_with(userinfo=b"")337 assert url.scheme == original_scheme338 assert url.userinfo == b""339 assert url.netloc == original_netloc340 assert url.raw_path == original_raw_path341 assert url.query == original_query342 assert url.fragment == original_fragment343318 url = httpx.URL("https://example.com/path?t=w#tw")345 original_userinfo = url.userinfo346 original_netloc = url.netloc347 original_raw_path = url.raw_path348 original_query = url.query349 original_fragment = url.fragment319 bad = "https://xxxx:xxxx@xxxxxxx/xxxxx/xxx?x=x#xxxxx"351 url = url.copy_with(scheme=bad)352 assert url.scheme == bad353 assert url.userinfo == original_userinfo354 assert url.netloc == original_netloc355 assert url.raw_path == original_raw_path356 assert url.query == original_query357 assert url.fragment == original_fragment320 with pytest.raises(httpx.InvalidURL):321 url.copy_with(scheme=bad)322323324def test_url_invalid():325 with pytest.raises(httpx.InvalidURL):
63 unmodified lines
389 assert url.netloc == b"[::ffff:192.168.0.1]"390 assert str(url) == "https://[::ffff:192.168.0.1]/"391392393def test_resolution_error_1833():394 """395 See https://github.com/encode/httpx/issues/1833396 """397 url = httpx.URL("https://example.com/?[]")398 assert url.join("/") == "https://example.com/"399400401def test_url_raw_compatibility():402 url = httpx.URL("https://www.example.com/path")403 scheme, host, port, raw_path = url.raw404
4 unmodified lines
modified:tests/test_asgi.py+1 added-1 removed
114 unmodified lines
115 url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")116 response = await client.get(url)117118 assert response.status_code == 200119 assert response.json() == {"raw_path": "/user%40example.org"}119 assert response.json() == {"raw_path": "/user@example.org"}120121122@pytest.mark.anyio123async def test_asgi_upload():
70 unmodified lines
added:tests/test_urlparse.py+232 added
1import pytest23import httpx4from httpx._urlparse import urlparse567def test_urlparse():8 url = urlparse("https://www.example.com/")910 assert url.scheme == "https"11 assert url.userinfo == ""12 assert url.netloc == "www.example.com"13 assert url.host == "www.example.com"14 assert url.port is None15 assert url.path == "/"16 assert url.query is None17 assert url.fragment is None1819 assert str(url) == "https://www.example.com/"202122def test_urlparse_no_scheme():23 url = urlparse("://example.com")24 assert url.scheme == ""25 assert url.host == "example.com"26 assert url.path == ""272829def test_urlparse_no_authority():30 url = urlparse("http://")31 assert url.scheme == "http"32 assert url.host == ""33 assert url.path == ""343536# Tests for different host types373839def test_urlparse_valid_host():40 url = urlparse("https://example.com/")41 assert url.host == "example.com"424344def test_urlparse_normalized_host():45 url = urlparse("https://EXAMPLE.com/")46 assert url.host == "example.com"474849def test_urlparse_valid_ipv4():50 url = urlparse("https://1.2.3.4/")51 assert url.host == "1.2.3.4"525354def test_urlparse_invalid_ipv4():55 with pytest.raises(httpx.InvalidURL) as exc:56 urlparse("https://999.999.999.999/")57 assert str(exc.value) == "Invalid IPv4 address"585960def test_urlparse_valid_ipv6():61 url = urlparse("https://[2001:db8::ff00:42:8329]/")62 assert url.host == "2001:db8::ff00:42:8329"636465def test_urlparse_invalid_ipv6():66 with pytest.raises(httpx.InvalidURL) as exc:67 urlparse("https://[2001]/")68 assert str(exc.value) == "Invalid IPv6 address"697071def test_urlparse_unescaped_idna_host():72 url = urlparse("https://中国.icom.museum/")73 assert url.host == "xn--fiqs8s.icom.museum"747576def test_urlparse_escaped_idna_host():77 url = urlparse("https://xn--fiqs8s.icom.museum/")78 assert url.host == "xn--fiqs8s.icom.museum"798081def test_urlparse_invalid_idna_host():82 with pytest.raises(httpx.InvalidURL) as exc:83 urlparse("https://☃.com/")84 assert str(exc.value) == "Invalid IDNA hostname"858687# Tests for different port types888990def test_urlparse_valid_port():91 url = urlparse("https://example.com:123/")92 assert url.port == 123939495def test_urlparse_normalized_port():96 # If the port matches the scheme default it is normalized to None.97 url = urlparse("https://example.com:443/")98 assert url.port is None99100101def test_urlparse_invalid_port():102 with pytest.raises(httpx.InvalidURL) as exc:103 urlparse("https://example.com:abc/")104 assert str(exc.value) == "Invalid port"105106107# Tests for path handling108109110def test_urlparse_normalized_path():111 url = urlparse("https://example.com/abc/def/../ghi/./jkl")112 assert url.path == "/abc/ghi/jkl"113114115def test_urlparse_escaped_path():116 url = urlparse("https://example.com/ /🌟/")117 assert url.path == "/%20/%F0%9F%8C%9F/"118119120def test_urlparse_leading_dot_prefix_on_absolute_url():121 url = urlparse("https://example.com/../abc")122 assert url.path == "/abc"123124125def test_urlparse_leading_dot_prefix_on_relative_url():126 url = urlparse("../abc")127 assert url.path == "../abc"128129130# Tests for invalid URLs131132133def test_urlparse_excessively_long_url():134 with pytest.raises(httpx.InvalidURL) as exc:135 urlparse("https://www.example.com/" + "x" * 100_000)136 assert str(exc.value) == "URL too long"137138139def test_urlparse_excessively_long_component():140 with pytest.raises(httpx.InvalidURL) as exc:141 urlparse("https://www.example.com", path="/" + "x" * 100_000)142 assert str(exc.value) == "URL component 'path' too long"143144145def test_urlparse_non_printing_character_in_url():146 with pytest.raises(httpx.InvalidURL) as exc:147 urlparse("https://www.example.com/\n")148 assert str(exc.value) == "Invalid non-printable ASCII character in URL"149150151def test_urlparse_non_printing_character_in_component():152 with pytest.raises(httpx.InvalidURL) as exc:153 urlparse("https://www.example.com", path="/\n")154 assert (155 str(exc.value)156 == "Invalid non-printable ASCII character in URL component 'path'"157 )158159160# Test for urlparse components161162163def test_urlparse_with_components():164 url = urlparse(scheme="https", host="www.example.com", path="/")165166 assert url.scheme == "https"167 assert url.userinfo == ""168 assert url.host == "www.example.com"169 assert url.port is None170 assert url.path == "/"171 assert url.query is None172 assert url.fragment is None173174 assert str(url) == "https://www.example.com/"175176177def test_urlparse_with_invalid_component():178 with pytest.raises(TypeError) as exc:179 urlparse(scheme="https", host="www.example.com", incorrect="/")180 assert str(exc.value) == "'incorrect' is an invalid keyword argument for urlparse()"181182183def test_urlparse_with_invalid_scheme():184 with pytest.raises(httpx.InvalidURL) as exc:185 urlparse(scheme="~", host="www.example.com", path="/")186 assert str(exc.value) == "Invalid URL component 'scheme'"187188189def test_urlparse_with_invalid_path():190 with pytest.raises(httpx.InvalidURL) as exc:191 urlparse(scheme="https", host="www.example.com", path="abc")192 assert str(exc.value) == "For absolute URLs, path must be empty or begin with '/'"193194 with pytest.raises(httpx.InvalidURL) as exc:195 urlparse(path="//abc")196 assert (197 str(exc.value)198 == "URLs with no authority component cannot have a path starting with '//'"199 )200201 with pytest.raises(httpx.InvalidURL) as exc:202 urlparse(path=":abc")203 assert (204 str(exc.value)205 == "URLs with no scheme component cannot have a path starting with ':'"206 )207208209def test_urlparse_with_relative_path():210 # This path would be invalid for an absolute URL, but is valid as a relative URL.211 url = urlparse(path="abc")212 assert url.path == "abc"213214215# Tests for accessing and modifying `urlparse` results.216217218def test_copy_with():219 url = urlparse("https://www.example.com/")220 assert str(url) == "https://www.example.com/"221222 url = url.copy_with()223 assert str(url) == "https://www.example.com/"224225 url = url.copy_with(scheme="http")226 assert str(url) == "http://www.example.com/"227228 url = url.copy_with(netloc="example.com")229 assert str(url) == "http://example.com/"230231 url = url.copy_with(path="/abc")232 assert str(url) == "http://example.com/abc"
modified:pyproject.toml+1 added-1 removed
28 unmodified lines
29]30dependencies = [31 "certifi",32 "httpcore>=0.15.0,<0.17.0",33 "rfc3986[idna2008]>=1.3,<2",33 "idna",34 "sniffio",35]36dynamic = ["readme", "version"]37
55 unmodified lines
modified:README.md+1 added-2 removed
126 unmodified lines
127128* `httpcore` - The underlying transport implementation for `httpx`.129 * `h11` - HTTP/1.1 support.130* `certifi` - SSL certificates.131* `rfc3986` - URL parsing & normalization.132 * `idna` - Internationalized domain name support.131* `idna` - Internationalized domain name support.132* `sniffio` - Async library autodetection.133134As well as these optional installs:135
13 unmodified lines