Graceful upgrade path for 0.28. (#3394)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parent 41597ad · Browse files · 11 files·+155 added−434 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+155 added−434 removed
- tests:+12 added−33 removed
- other:+143 added−401 removed
Provenance
- Commit
1805ee0- Tree
162f687- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
41597ad
11 files changed+155 added−434 removed
modified:docs/advanced/ssl.md+42 added-140 removed
7 unmodified lines8910111212131415161718192021222324252627281516171819203421223637383923244125264327282930314546474849505152535455563233343536593738616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111394041424344117118454647481214950511245253541271285556575859131606113362631356465661381391401411421431441456768697071148727315074751527677154155156157781591601611621637980818283848586871661671681691701711721731741751761771781791801818889909118692939495190969719219319419519619719898991001017 unmodified lines>>> httpx.get("https://expired.badssl.com/")httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)```
Verification is configured through [the SSL Context API](https://docs.python.org/3/library/ssl.html#ssl-contexts).You can disable SSL verification completely and allow insecure requests...
```pycon>>> context = httpx.SSLContext()>>> context<SSLContext(verify=True)>>>> httpx.get("https://www.example.com", ssl_context=context)httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)```
You can use this to disable verification completely and allow insecure requests...
```pycon>>> context = httpx.SSLContext(verify=False)>>> context<SSLContext(verify=False)>>>> httpx.get("https://expired.badssl.com/", ssl_context=context)>>> httpx.get("https://expired.badssl.com/", verify=False)<Response [200 OK]>```
### Configuring client instances
If you're using a `Client()` instance you should pass any SSL context when instantiating the client.If you're using a `Client()` instance you should pass any `verify=<...>` configuration when instantiating the client.
```pycon>>> context = httpx.SSLContext()>>> client = httpx.Client(ssl_context=context)```By default the [certifi CA bundle](https://certifiio.readthedocs.io/en/latest/) is used for SSL verification.
The `client.get(...)` method and other request methods on a `Client` instance *do not* support changing the SSL settings on a per-request basis.For more complex configurations you can pass an [SSL Context](https://docs.python.org/3/library/ssl.html) instance...
If you need different SSL settings in different cases you should use more than one client instance, with different settings on each. Each client will then be using an isolated connection pool with a specific fixed SSL configuration on all connections within that pool.```pythonimport certifiimport httpximport ssl
### Configuring certificate stores
By default, HTTPX uses the CA bundle provided by [Certifi](https://pypi.org/project/certifi/).
You can load additional certificate verification using the [`.load_verify_locations()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_verify_locations) API:
```pycon>>> context = httpx.SSLContext()>>> context.load_verify_locations(cafile="path/to/certs.pem")>>> client = httpx.Client(ssl_context=context)>>> client.get("https://www.example.com")<Response [200 OK]># This SSL context is equivelent to the default `verify=True`.ctx = ssl.create_default_context(cafile=certifi.where())client = httpx.Client(verify=ctx)```
Or by providing an certificate directory:Using [the `truststore` package](https://truststore.readthedocs.io/) to support system certificate stores...
```pycon>>> context = httpx.SSLContext()>>> context.load_verify_locations(capath="path/to/certs")>>> client = httpx.Client(ssl_context=context)>>> client.get("https://www.example.com")<Response [200 OK]>```
### Client side certificates
You can also specify a local cert to use as a client-side certificate, using the [`.load_cert_chain()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_cert_chain) API:
```pycon>>> context = httpx.SSLContext()>>> context.load_cert_chain(certfile="path/to/client.pem")>>> httpx.get("https://example.org", ssl_context=ssl_context)<Response [200 OK]>```
Or including a keyfile...
```pycon>>> context = httpx.SSLContext()>>> context.load_cert_chain( certfile="path/to/client.pem", keyfile="path/to/client.key" )>>> httpx.get("https://example.org", ssl_context=context)<Response [200 OK]>```
Or including a keyfile and password...
```pycon>>> context = httpx.SSLContext(cert=cert)>>> context = httpx.SSLContext()>>> context.load_cert_chain( certfile="path/to/client.pem", keyfile="path/to/client.key" password="password" )>>> httpx.get("https://example.org", ssl_context=context)<Response [200 OK]>```
### Using alternate SSL contexts
You can also use an alternate `ssl.SSLContext` instances.
For example, [using the `truststore` package](https://truststore.readthedocs.io/)...
```pythonimport sslimport truststoreimport httpx
# Use system certificate stores.ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)client = httpx.Client(ssl_context=ssl_context)ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)client = httpx.Client(verify=ctx)```
Or working [directly with Python's standard library](https://docs.python.org/3/library/ssl.html)...Loding an alternative certificate verification store using [the standard SSL context API](https://docs.python.org/3/library/ssl.html)...
```pythonimport sslimport httpximport ssl
ssl_context = ssl.create_default_context()client = httpx.Client(ssl_context=ssl_context)# Use an explicitly configured certificate store.ctx = ssl.create_default_context(cafile="path/to/certs.pem") # Either cafile or capath.client = httpx.Client(verify=ctx)```
### Working with `SSL_CERT_FILE` and `SSL_CERT_DIR`### Client side certificates
Unlike `requests`, the `httpx` package does not automatically pull in [the environment variables `SSL_CERT_FILE` or `SSL_CERT_DIR`](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_default_verify_paths.html). If you want to use these they need to be enabled explicitly.Client side certificates allow a remote server to verify the client. They tend to be used within private organizations to authenticate requests to remote servers.
For example...You can specify client-side certificates, using the [`.load_cert_chain()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_cert_chain) API...
```pythoncontext = httpx.SSLContext()
# Use `SSL_CERT_FILE` or `SSL_CERT_DIR` if configured.if os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR"): context.load_verify_locations( cafile=os.environ.get("SSL_CERT_FILE"), capath=os.environ.get("SSL_CERT_DIR"), )ctx = ssl.create_default_context()ctx.load_cert_chain(certfile="path/to/client.pem") # Optionally also keyfile or password.client = httpx.Client(verify=ctx)```
## `SSLKEYLOGFILE`### Working with `SSL_CERT_FILE` and `SSL_CERT_DIR`
Valid values: a filenameUnlike `requests`, the `httpx` package does not automatically pull in [the environment variables `SSL_CERT_FILE` or `SSL_CERT_DIR`](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_default_verify_paths.html). If you want to use these they need to be enabled explicitly.
If this environment variable is set, TLS keys will be appended to the specified file, creating it if it doesn't exist, whenever key material is generated or received. The keylog file is designed for debugging purposes only.For example...
Support for `SSLKEYLOGFILE` requires Python 3.8 and OpenSSL 1.1.1 or newer.
Example:
```python# test_script.pyimport httpx
with httpx.Client() as client: r = client.get("https://google.com")# Use `SSL_CERT_FILE` or `SSL_CERT_DIR` if configured.# Otherwise default to certifi.ctx = ssl.create_default_context( cafile=os.environ.get("SSL_CERT_FILE", certifi.where()), capath=os.environ.get("SSL_CERT_DIR"),)client = httpx.Client(verify=ctx)```
```consoleSSLKEYLOGFILE=test.log python test_script.pycat test.log# TLS secrets log file, generated by OpenSSL / PythonSERVER_HANDSHAKE_TRAFFIC_SECRET XXXXEXPORTER_SECRET XXXXSERVER_TRAFFIC_SECRET_0 XXXXCLIENT_HANDSHAKE_TRAFFIC_SECRET XXXXCLIENT_TRAFFIC_SECRET_0 XXXXSERVER_HANDSHAKE_TRAFFIC_SECRET XXXXEXPORTER_SECRET XXXXSERVER_TRAFFIC_SECRET_0 XXXXCLIENT_HANDSHAKE_TRAFFIC_SECRET XXXXCLIENT_TRAFFIC_SECRET_0 XXXX```
### Making HTTPS requests to a local server
When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.
If you do need to make HTTPS connections to a local server, for example to test an HTTPS-only service, you will need to create and use your own certificates. Here's one way to do it:If you do need to make HTTPS connections to a local server, for example to test an HTTPS-only service, you will need to create and use your own certificates. Here's one way to do it...
1. Use [trustme](https://github.com/python-trio/trustme) to generate a pair of server key/cert files, and a client cert file.2. Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, [Uvicorn](https://www.uvicorn.org) provides the `--ssl-keyfile` and `--ssl-certfile` options.)3. Tell HTTPX to use the certificates stored in `client.pem`:3. Configure `httpx` to use the certificates stored in `client.pem`.
```pycon>>> import httpx>>> context = httpx.SSLContext()>>> context.load_verify_locations(cafile="/tmp/client.pem")>>> r = httpx.get("https://localhost:8000", ssl_context=context)>>> rResponse <200 OK>```pythonctx = ssl.create_default_context(cafile="client.pem")client = httpx.Client(verify=ctx)```modified:docs/contributing.md+3 added-6 removed
208 unmodified lines209 [proxy section](https://www.python-httpx.org/advanced/proxies/#http-proxies) and210 the [SSL certificates section](https://www.python-httpx.org/advanced/ssl/),211 this is where our previously generated `client.pem` comes in:212 213+```python214+ctx = ssl.create_default_context(cafile="/path/to/client.pem")215+client = httpx.Client(proxy="http://127.0.0.1:8080/", verify=ctx)216 ```214-import httpx217 216-with httpx.Client(proxy="http://127.0.0.1:8080/", verify="/path/to/client.pem") as client:217- response = client.get("https://example.org")218- print(response.status_code) # should print 200219-```220-218 Note, however, that HTTPS requests will only succeed to the host specified219 in the SSL/TLS certificate we generated, HTTPS requests to other hosts will220 raise an error like:221 11 unmodified linesmodified:httpx/_transports/default.py+5 added-19 removed
33 unmodified lines34 import ssl # pragma: no cover35 36 import httpx # pragma: no cover37 38-from .._config import DEFAULT_LIMITS, Limits, Proxy, SSLContext, create_ssl_context38+from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context39 from .._exceptions import (40 ConnectError,41 ConnectTimeout,42 LocalProtocolError,91 unmodified lines134 135 class HTTPTransport(BaseTransport):136 def __init__(137 self,138- ssl_context: ssl.SSLContext | None = None,138+ verify: ssl.SSLContext | bool = True,139 http1: bool = True,140 http2: bool = False,141 limits: Limits = DEFAULT_LIMITS,142 proxy: ProxyTypes | None = None,143 uds: str | None = None,144 local_address: str | None = None,145 retries: int = 0,146 socket_options: typing.Iterable[SOCKET_OPTION] | None = None,147- # Deprecated...148- verify: typing.Any = None,149- cert: typing.Any = None,147 ) -> None:148 import httpcore149 150 proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy154- if verify is not None or cert is not None: # pragma: nocover155- # Deprecated...156- ssl_context = create_ssl_context(verify, cert)151+ ssl_context = create_ssl_context(verify=verify)157- else:158- ssl_context = ssl_context or SSLContext()152 153 if proxy is None:154 self._pool = httpcore.ConnectionPool(155 ssl_context=ssl_context,120 unmodified lines276 277 class AsyncHTTPTransport(AsyncBaseTransport):278 def __init__(279 self,287- ssl_context: ssl.SSLContext | None = None,280+ verify: ssl.SSLContext | bool = True,281 http1: bool = True,282 http2: bool = False,283 limits: Limits = DEFAULT_LIMITS,284 proxy: ProxyTypes | None = None,285 uds: str | None = None,286 local_address: str | None = None,287 retries: int = 0,288 socket_options: typing.Iterable[SOCKET_OPTION] | None = None,296- # Deprecated...297- verify: typing.Any = None,298- cert: typing.Any = None,289 ) -> None:290 import httpcore291 292 proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy303- if verify is not None or cert is not None: # pragma: nocover304- # Deprecated...305- ssl_context = create_ssl_context(verify, cert)293+ ssl_context = create_ssl_context(verify=verify)306- else:307- ssl_context = ssl_context or SSLContext()294 295 if proxy is None:296 self._pool = httpcore.AsyncConnectionPool(297 ssl_context=ssl_context,105 unmodified linesmodified:httpx/__init__.py-1 removed
79 unmodified lines80 "RequestError",81 "RequestNotRead",82 "Response",83 "ResponseNotRead",84- "SSLContext",84 "stream",85 "StreamClosed",86 "StreamConsumed",87 "StreamError",18 unmodified linesmodified:httpx/_api.py+25 added-66 removed
1 from __future__ import annotations2 3-import ssl3 import typing4 from contextlib import contextmanager5 6 from ._client import Client11 unmodified lines18 TimeoutTypes,19 )20 from ._urls import URL21 22+if typing.TYPE_CHECKING:23+ import ssl # pragma: no cover24+25+26 __all__ = [27 "delete",28 "get",29 "head",20 unmodified lines50 auth: AuthTypes | None = None,51 proxy: ProxyTypes | None = None,52 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,53 follow_redirects: bool = False,51- ssl_context: ssl.SSLContext | None = None,54+ verify: ssl.SSLContext | bool = True,55 trust_env: bool = True,53- # Deprecated in favor of `ssl_context`...54- verify: typing.Any = None,55- cert: typing.Any = None,56 ) -> Response:57 """58 Sends an HTTP request.59 21 unmodified lines81 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.82 * **timeout** - *(optional)* The timeout configuration to use when sending83 the request.84 * **follow_redirects** - *(optional)* Enables or disables HTTP redirects.85- * **ssl_context** - *(optional)* An SSL certificate used by the requested host86- to authenticate the client.85+ * **verify** - *(optional)* Either `True` to use an SSL context with the86+ default CA bundle, `False` to disable verification, or an instance of87+ `ssl.SSLContext` to use a custom context.88 * **trust_env** - *(optional)* Enables or disables usage of environment89 variables for configuration.90 91 **Returns:** `Response`9 unmodified lines101 """102 with Client(103 cookies=cookies,104 proxy=proxy,104- ssl_context=ssl_context,105+ verify=verify,106 timeout=timeout,107 trust_env=trust_env,107- verify=verify,108- cert=cert,108 ) as client:109 return client.request(110 method=method,111 url=url,23 unmodified lines135 auth: AuthTypes | None = None,136 proxy: ProxyTypes | None = None,137 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,138 follow_redirects: bool = False,140- ssl_context: ssl.SSLContext | None = None,139+ verify: ssl.SSLContext | bool = True,140 trust_env: bool = True,142- # Deprecated in favor of `ssl_context`...143- verify: typing.Any = None,144- cert: typing.Any = None,141 ) -> typing.Iterator[Response]:142 """143 Alternative to `httpx.request()` that streams the response body144 instead of loading it into memory at once.6 unmodified lines151 """152 with Client(153 cookies=cookies,154 proxy=proxy,159- ssl_context=ssl_context,155+ verify=verify,156 timeout=timeout,157 trust_env=trust_env,162- verify=verify,163- cert=cert,158 ) as client:159 with client.stream(160 method=method,161 url=url,17 unmodified lines179 cookies: CookieTypes | None = None,180 auth: AuthTypes | None = None,181 proxy: ProxyTypes | None = None,182 follow_redirects: bool = False,189- ssl_context: ssl.SSLContext | None = None,183+ verify: ssl.SSLContext | bool = True,184 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,185 trust_env: bool = True,192- # Deprecated in favor of `ssl_context`...193- verify: typing.Any = None,194- cert: typing.Any = None,186 ) -> Response:187 """188 Sends a `GET` request.189 10 unmodified lines200 cookies=cookies,201 auth=auth,202 proxy=proxy,203 follow_redirects=follow_redirects,213- ssl_context=ssl_context,204+ verify=verify,205 timeout=timeout,206 trust_env=trust_env,216- verify=verify,217- cert=cert,207 )208 209 210 def options(4 unmodified lines215 cookies: CookieTypes | None = None,216 auth: AuthTypes | None = None,217 proxy: ProxyTypes | None = None,218 follow_redirects: bool = False,230- ssl_context: ssl.SSLContext | None = None,219+ verify: ssl.SSLContext | bool = True,220 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,221 trust_env: bool = True,233- # Deprecated in favor of `ssl_context`...234- verify: typing.Any = None,235- cert: typing.Any = None,222 ) -> Response:223 """224 Sends an `OPTIONS` request.225 10 unmodified lines236 cookies=cookies,237 auth=auth,238 proxy=proxy,239 follow_redirects=follow_redirects,254- ssl_context=ssl_context,240+ verify=verify,241 timeout=timeout,242 trust_env=trust_env,257- verify=verify,258- cert=cert,243 )244 245 246 def head(4 unmodified lines251 cookies: CookieTypes | None = None,252 auth: AuthTypes | None = None,253 proxy: ProxyTypes | None = None,254 follow_redirects: bool = False,271- ssl_context: ssl.SSLContext | None = None,255+ verify: ssl.SSLContext | bool = True,256 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,257 trust_env: bool = True,274- # Deprecated in favor of `ssl_context`...275- verify: typing.Any = None,276- cert: typing.Any = None,258 ) -> Response:259 """260 Sends a `HEAD` request.261 10 unmodified lines272 cookies=cookies,273 auth=auth,274 proxy=proxy,275 follow_redirects=follow_redirects,295- ssl_context=ssl_context,276+ verify=verify,277 timeout=timeout,278 trust_env=trust_env,298- verify=verify,299- cert=cert,279 )280 281 282 def post(8 unmodified lines291 cookies: CookieTypes | None = None,292 auth: AuthTypes | None = None,293 proxy: ProxyTypes | None = None,294 follow_redirects: bool = False,316- ssl_context: ssl.SSLContext | None = None,295+ verify: ssl.SSLContext | bool = True,296 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,297 trust_env: bool = True,319- # Deprecated in favor of `ssl_context`...320- verify: typing.Any = None,321- cert: typing.Any = None,298 ) -> Response:299 """300 Sends a `POST` request.301 11 unmodified lines313 cookies=cookies,314 auth=auth,315 proxy=proxy,316 follow_redirects=follow_redirects,341- ssl_context=ssl_context,317+ verify=verify,318 timeout=timeout,319 trust_env=trust_env,344- verify=verify,345- cert=cert,320 )321 322 323 def put(8 unmodified lines332 cookies: CookieTypes | None = None,333 auth: AuthTypes | None = None,334 proxy: ProxyTypes | None = None,335 follow_redirects: bool = False,362- ssl_context: ssl.SSLContext | None = None,336+ verify: ssl.SSLContext | bool = True,337 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,338 trust_env: bool = True,365- # Deprecated in favor of `ssl_context`...366- verify: typing.Any = None,367- cert: typing.Any = None,339 ) -> Response:340 """341 Sends a `PUT` request.342 11 unmodified lines354 cookies=cookies,355 auth=auth,356 proxy=proxy,357 follow_redirects=follow_redirects,387- ssl_context=ssl_context,358+ verify=verify,359 timeout=timeout,360 trust_env=trust_env,390- verify=verify,391- cert=cert,361 )362 363 364 def patch(8 unmodified lines373 cookies: CookieTypes | None = None,374 auth: AuthTypes | None = None,375 proxy: ProxyTypes | None = None,376 follow_redirects: bool = False,408- ssl_context: ssl.SSLContext | None = None,377+ verify: ssl.SSLContext | bool = True,378 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,379 trust_env: bool = True,411- # Deprecated in favor of `ssl_context`...412- verify: typing.Any = None,413- cert: typing.Any = None,380 ) -> Response:381 """382 Sends a `PATCH` request.383 11 unmodified lines395 cookies=cookies,396 auth=auth,397 proxy=proxy,398 follow_redirects=follow_redirects,433- ssl_context=ssl_context,399+ verify=verify,400 timeout=timeout,401 trust_env=trust_env,436- verify=verify,437- cert=cert,402 )403 404 405 def delete(5 unmodified lines411 auth: AuthTypes | None = None,412 proxy: ProxyTypes | None = None,413 follow_redirects: bool = False,414 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,451- ssl_context: ssl.SSLContext | None = None,415+ verify: ssl.SSLContext | bool = True,416 trust_env: bool = True,453- # Deprecated in favor of `ssl_context`...454- verify: typing.Any = None,455- cert: typing.Any = None,417 ) -> Response:418 """419 Sends a `DELETE` request.420 10 unmodified lines431 cookies=cookies,432 auth=auth,433 proxy=proxy,434 follow_redirects=follow_redirects,474- ssl_context=ssl_context,435+ verify=verify,436 timeout=timeout,437 trust_env=trust_env,477- verify=verify,478- cert=cert,438 )modified:httpx/_client.py+23 added-60 removed
1 unmodified line2 3 import datetime4 import enum5 import logging6-import ssl6 import time7 import typing8 import warnings9 from contextlib import asynccontextmanager, contextmanager41 unmodified lines51 is_https_redirect,52 same_origin,53 )54 55+if typing.TYPE_CHECKING:56+ import ssl # pragma: no cover57+58 __all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"]59 60 # The type annotation for @classmethod and context managers here follows PEP 48461 # https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods523 unmodified lines585 * **headers** - *(optional)* Dictionary of HTTP headers to include when586 sending requests.587 * **cookies** - *(optional)* Dictionary of Cookie items to include when588 sending requests.587- * **ssl_context** - *(optional)* An SSL certificate used by the requested host588- to authenticate the client.589+ * **verify** - *(optional)* Either `True` to use an SSL context with the590+ default CA bundle, `False` to disable verification, or an instance of591+ `ssl.SSLContext` to use a custom context.592 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be593 enabled. Defaults to `False`.594 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.595 * **proxies** - *(optional)* A dictionary mapping proxy keys to proxy20 unmodified lines616 auth: AuthTypes | None = None,617 params: QueryParamTypes | None = None,618 headers: HeaderTypes | None = None,619 cookies: CookieTypes | None = None,617- ssl_context: ssl.SSLContext | None = None,620+ verify: ssl.SSLContext | bool = True,621 http1: bool = True,622 http2: bool = False,623 proxy: ProxyTypes | None = None,624 mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,5 unmodified lines630 base_url: URL | str = "",631 transport: BaseTransport | None = None,632 trust_env: bool = True,633 default_encoding: str | typing.Callable[[bytes], str] = "utf-8",631- # Deprecated in favor of `ssl_context`...632- verify: typing.Any = None,633- cert: typing.Any = None,634 ) -> None:635 super().__init__(636 auth=auth,637 params=params,20 unmodified lines658 allow_env_proxies = trust_env and transport is None659 proxy_map = self._get_proxy_map(proxy, allow_env_proxies)660 661 self._transport = self._init_transport(662- ssl_context=ssl_context,662+ verify=verify,663 http1=http1,664 http2=http2,665 limits=limits,666 transport=transport,667- trust_env=trust_env,668- # Deprecated in favor of ssl_context...669- verify=verify,670- cert=cert,667 )668 self._mounts: dict[URLPattern, BaseTransport | None] = {669 URLPattern(key): None670 if proxy is None671 else self._init_proxy_transport(672 proxy,677- ssl_context=ssl_context,673+ verify=verify,674 http1=http1,675 http2=http2,676 limits=limits,681- # Deprecated in favor of ssl_context...682- verify=verify,683- cert=cert,677 )678 for key, proxy in proxy_map.items()679 }680 if mounts is not None:4 unmodified lines685 self._mounts = dict(sorted(self._mounts.items()))686 687 def _init_transport(688 self,696- ssl_context: ssl.SSLContext | None = None,689+ verify: ssl.SSLContext | bool = True,690 http1: bool = True,691 http2: bool = False,692 limits: Limits = DEFAULT_LIMITS,693 transport: BaseTransport | None = None,701- trust_env: bool = True,702- # Deprecated in favor of `ssl_context`...703- verify: typing.Any = None,704- cert: typing.Any = None,694 ) -> BaseTransport:695 if transport is not None:696 return transport697 698 return HTTPTransport(710- ssl_context=ssl_context,699+ verify=verify,700 http1=http1,701 http2=http2,702 limits=limits,714- verify=verify,715- cert=cert,703 )704 705 def _init_proxy_transport(706 self,707 proxy: Proxy,721- ssl_context: ssl.SSLContext | None = None,708+ verify: ssl.SSLContext | bool = True,709 http1: bool = True,710 http2: bool = False,711 limits: Limits = DEFAULT_LIMITS,725- trust_env: bool = True,726- # Deprecated in favor of `ssl_context`...727- verify: typing.Any = None,728- cert: typing.Any = None,712 ) -> BaseTransport:713 return HTTPTransport(731- ssl_context=ssl_context,714+ verify=verify,715 http1=http1,716 http2=http2,717 limits=limits,718 proxy=proxy,736- verify=verify,737- cert=cert,719 )720 721 def _transport_for_url(self, url: URL) -> BaseTransport:722 """565 unmodified lines1288 * **headers** - *(optional)* Dictionary of HTTP headers to include when1289 sending requests.1290 * **cookies** - *(optional)* Dictionary of Cookie items to include when1291 sending requests.1311- * **ssl_context** - *(optional)* An SSL certificate used by the requested host1312- to authenticate the client.1292+ * **verify** - *(optional)* Either `True` to use an SSL context with the1293+ default CA bundle, `False` to disable verification, or an instance of1294+ `ssl.SSLContext` to use a custom context.1295 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be1296 enabled. Defaults to `False`.1297 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.1298 * **timeout** - *(optional)* The timeout configuration to use when sending18 unmodified lines1317 auth: AuthTypes | None = None,1318 params: QueryParamTypes | None = None,1319 headers: HeaderTypes | None = None,1320 cookies: CookieTypes | None = None,1339- ssl_context: ssl.SSLContext | None = None,1321+ verify: ssl.SSLContext | bool = True,1322 http1: bool = True,1323 http2: bool = False,1324 proxy: ProxyTypes | None = None,1325 mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None,5 unmodified lines1331 base_url: URL | str = "",1332 transport: AsyncBaseTransport | None = None,1333 trust_env: bool = True,1334 default_encoding: str | typing.Callable[[bytes], str] = "utf-8",1353- # Deprecated in favor of `ssl_context`...1354- verify: typing.Any = None,1355- cert: typing.Any = None,1335 ) -> None:1336 super().__init__(1337 auth=auth,1338 params=params,20 unmodified lines1359 allow_env_proxies = trust_env and transport is None1360 proxy_map = self._get_proxy_map(proxy, allow_env_proxies)1361 1362 self._transport = self._init_transport(1384- ssl_context=ssl_context,1363+ verify=verify,1364 http1=http1,1365 http2=http2,1366 limits=limits,1367 transport=transport,1389- # Deprecated in favor of ssl_context1390- verify=verify,1391- cert=cert,1368 )1369 1370 self._mounts: dict[URLPattern, AsyncBaseTransport | None] = {1371 URLPattern(key): None1372 if proxy is None1373 else self._init_proxy_transport(1374 proxy,1399- ssl_context=ssl_context,1375+ verify=verify,1376 http1=http1,1377 http2=http2,1378 limits=limits,1403- # Deprecated in favor of `ssl_context`...1404- verify=verify,1405- cert=cert,1379 )1380 for key, proxy in proxy_map.items()1381 }1382 if mounts is not None:3 unmodified lines1386 self._mounts = dict(sorted(self._mounts.items()))1387 1388 def _init_transport(1389 self,1417- ssl_context: ssl.SSLContext | None = None,1390+ verify: ssl.SSLContext | bool = True,1391 http1: bool = True,1392 http2: bool = False,1393 limits: Limits = DEFAULT_LIMITS,1394 transport: AsyncBaseTransport | None = None,1422- # Deprecated in favor of `ssl_context`...1423- verify: typing.Any = None,1424- cert: typing.Any = None,1395 ) -> AsyncBaseTransport:1396 if transport is not None:1397 return transport1398 1399 return AsyncHTTPTransport(1430- ssl_context=ssl_context,1400+ verify=verify,1401 http1=http1,1402 http2=http2,1403 limits=limits,1434- verify=verify,1435- cert=cert,1404 )1405 1406 def _init_proxy_transport(1407 self,1408 proxy: Proxy,1441- ssl_context: ssl.SSLContext | None = None,1409+ verify: ssl.SSLContext | bool = True,1410 http1: bool = True,1411 http2: bool = False,1412 limits: Limits = DEFAULT_LIMITS,1445- # Deprecated in favor of `ssl_context`...1446- verify: typing.Any = None,1447- cert: typing.Any = None,1413 ) -> AsyncBaseTransport:1414 return AsyncHTTPTransport(1450- ssl_context=ssl_context,1415+ verify=verify,1416 http1=http1,1417 http2=http2,1418 limits=limits,1419 proxy=proxy,1455- verify=verify,1456- cert=cert,1420 )1421 1422 def _transport_for_url(self, url: URL) -> AsyncBaseTransport:1423 """544 unmodified linesmodified:httpx/_config.py+12 added-100 removed
1 from __future__ import annotations2 3-import os3 import ssl5-import sys4 import typing7-import warnings5 6 from ._models import Headers7 from ._types import HeaderTypes, TimeoutTypes8 from ._urls import URL9 13-__all__ = ["Limits", "Proxy", "SSLContext", "Timeout", "create_ssl_context"]10+__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"]11 12 13 class UnsetType:14 pass # pragma: no cover1 unmodified line16 17 UNSET = UnsetType()18 19 23-def create_ssl_context(24- verify: typing.Any = None,25- cert: typing.Any = None,26- trust_env: bool = True,27- http2: bool = False,28-) -> ssl.SSLContext: # pragma: nocover29- # The `create_ssl_context` helper function is now deprecated30- # in favour of `httpx.SSLContext()`.31- if isinstance(verify, bool):32- ssl_context: ssl.SSLContext = SSLContext(verify=verify)33- warnings.warn(34- "The verify=<bool> parameter is deprecated since 0.28.0. "35- "Use `ssl_context=httpx.SSLContext(verify=<bool>)`."36- )37- elif isinstance(verify, str):38- warnings.warn(39- "The verify=<str> parameter is deprecated since 0.28.0. "40- "Use `ssl_context=httpx.SSLContext()` and `.load_verify_locations()`."41- )42- ssl_context = SSLContext()43- if os.path.isfile(verify):44- ssl_context.load_verify_locations(cafile=verify)45- elif os.path.isdir(verify):46- ssl_context.load_verify_locations(capath=verify)47- elif isinstance(verify, ssl.SSLContext):48- warnings.warn(49- "The verify=<ssl context> parameter is deprecated since 0.28.0. "50- "Use `ssl_context = httpx.SSLContext()`."51- )52- ssl_context = verify53- else:54- warnings.warn(55- "`create_ssl_context()` is deprecated since 0.28.0."56- "Use `ssl_context = httpx.SSLContext()`."57- )58- ssl_context = SSLContext()20+def create_ssl_context(verify: ssl.SSLContext | bool = True) -> ssl.SSLContext:21+ import ssl22 60- if cert is not None:61- warnings.warn(62- "The `cert=<...>` parameter is deprecated since 0.28.0. "63- "Use `ssl_context = httpx.SSLContext()` and `.load_cert_chain()`."64- )65- if isinstance(cert, str):66- ssl_context.load_cert_chain(cert)67- else:68- ssl_context.load_cert_chain(*cert)23+ import certifi24 25+ if verify is True:26+ return ssl.create_default_context(cafile=certifi.where())27+ elif verify is False:28+ ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)29+ ssl_context.check_hostname = False30+ ssl_context.verify_mode = ssl.CERT_NONE70- return ssl_context31+ return ssl_context32 33+ return verify34 73-class SSLContext(ssl.SSLContext):74- def __init__(75- self,76- verify: bool = True,77- ) -> None:78- import certifi35 80- # ssl.SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,81- # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE82- # by default. (from `ssl.create_default_context`)83- super().__init__()84- self._verify = verify85-86- # Our SSL setup here is similar to the stdlib `ssl.create_default_context()`87- # implementation, except with `certifi` used for certificate verification.88- if not verify:89- self.check_hostname = False90- self.verify_mode = ssl.CERT_NONE91- return92-93- self.verify_mode = ssl.CERT_REQUIRED94- self.check_hostname = True95-96- # Use stricter verify flags where possible.97- if hasattr(ssl, "VERIFY_X509_PARTIAL_CHAIN"): # pragma: nocover98- self.verify_flags |= ssl.VERIFY_X509_PARTIAL_CHAIN99- if hasattr(ssl, "VERIFY_X509_STRICT"): # pragma: nocover100- self.verify_flags |= ssl.VERIFY_X509_STRICT101-102- # Default to `certifi` for certificiate verification.103- self.load_verify_locations(cafile=certifi.where())104-105- # OpenSSL keylog file support.106- if hasattr(self, "keylog_filename"):107- keylogfile = os.environ.get("SSLKEYLOGFILE")108- if keylogfile and not sys.flags.ignore_environment:109- self.keylog_filename = keylogfile110-111- def __repr__(self) -> str:112- class_name = self.__class__.__name__113- return f"<{class_name}(verify={self._verify!r})>"114-115- def __new__(116- cls,117- protocol: ssl._SSLMethod = ssl.PROTOCOL_TLS_CLIENT,118- *args: typing.Any,119- **kwargs: typing.Any,120- ) -> "SSLContext":121- return super().__new__(cls, protocol, *args, **kwargs)122-123-36 class Timeout:37 """38 Timeout configuration.39 173 unmodified linesmodified:httpx/_main.py+1 added-5 removed
13 unmodified lines14 import rich.syntax15 import rich.table16 17 from ._client import Client18-from ._config import SSLContext18 from ._exceptions import RequestError19 from ._models import Response20 from ._status_codes import codes21 452 unmodified lines474 """475 if not method:476 method = "POST" if content or data or files or json else "GET"477 479- ssl_context = SSLContext(verify=verify)478 try:481- with Client(482- proxy=proxy, timeout=timeout, http2=http2, ssl_context=ssl_context483- ) as client:479+ with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client:480 with client.stream(481 method,482 url,483 params=list(params),23 unmodified linesmodified:httpx/_urls.py+16 added
398 unmodified lines399 )400 401 return f"{self.__class__.__name__}({url!r})"402 403+ @property404+ def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover405+ import collections406+ import warnings407 408+ warnings.warn("URL.raw is deprecated.")409+ RawURL = collections.namedtuple(410+ "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"]411+ )412+ return RawURL(413+ raw_scheme=self.raw_scheme,414+ raw_host=self.raw_host,415+ port=self.port,416+ raw_path=self.raw_path,417+ )418+419+420 class QueryParams(typing.Mapping[str, str]):421 """422 URL query parameters, as a multi-dict.423 """218 unmodified linesmodified:tests/test_config.py+12 added-33 removed
7 unmodified lines8 import httpx9 10 11 def test_load_ssl_config():12- context = httpx.SSLContext()12+ context = httpx.create_ssl_context()13 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED14 assert context.check_hostname is True15 16 17 def test_load_ssl_config_verify_non_existing_file():18 with pytest.raises(IOError):19- context = httpx.SSLContext()19+ context = httpx.create_ssl_context()20 context.load_verify_locations(cafile="/path/to/nowhere")21 22 23 def test_load_ssl_with_keylog(monkeypatch: typing.Any) -> None:24 monkeypatch.setenv("SSLKEYLOGFILE", "test")25- context = httpx.SSLContext()25+ context = httpx.create_ssl_context()26 assert context.keylog_filename == "test"27 28 29 def test_load_ssl_config_verify_existing_file():30- context = httpx.SSLContext()30+ context = httpx.create_ssl_context()31 context.load_verify_locations(capath=certifi.where())32 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED33 assert context.check_hostname is True34 35 36 def test_load_ssl_config_verify_directory():37- context = httpx.SSLContext()37+ context = httpx.create_ssl_context()38 context.load_verify_locations(capath=Path(certifi.where()).parent)39 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED40 assert context.check_hostname is True41 42 43 def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):44- context = httpx.SSLContext()44+ context = httpx.create_ssl_context()45 context.load_cert_chain(cert_pem_file, cert_private_key_file)46 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED47 assert context.check_hostname is True48 1 unmodified line50 @pytest.mark.parametrize("password", [b"password", "password"])51 def test_load_ssl_config_cert_and_encrypted_key(52 cert_pem_file, cert_encrypted_private_key_file, password53 ):54- context = httpx.SSLContext()54+ context = httpx.create_ssl_context()55 context.load_cert_chain(cert_pem_file, cert_encrypted_private_key_file, password)56 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED57 assert context.check_hostname is True58 1 unmodified line60 def test_load_ssl_config_cert_and_key_invalid_password(61 cert_pem_file, cert_encrypted_private_key_file62 ):63 with pytest.raises(ssl.SSLError):64- context = httpx.SSLContext()64+ context = httpx.create_ssl_context()65 context.load_cert_chain(66 cert_pem_file, cert_encrypted_private_key_file, "password1"67 )68 69 70 def test_load_ssl_config_cert_without_key_raises(cert_pem_file):71 with pytest.raises(ssl.SSLError):72- context = httpx.SSLContext()72+ context = httpx.create_ssl_context()73 context.load_cert_chain(cert_pem_file)74 75 76 def test_load_ssl_config_no_verify():77- context = httpx.SSLContext(verify=False)77+ context = httpx.create_ssl_context(verify=False)78 assert context.verify_mode == ssl.VerifyMode.CERT_NONE79 assert context.check_hostname is False80 81 82 def test_SSLContext_with_get_request(server, cert_pem_file):83- context = httpx.SSLContext()83+ context = httpx.create_ssl_context()84 context.load_verify_locations(cert_pem_file)85- response = httpx.get(server.url, ssl_context=context)85+ response = httpx.get(server.url, verify=context)86 assert response.status_code == 20087 88 89-def test_SSLContext_repr():90- ssl_context = httpx.SSLContext()91-92- assert repr(ssl_context) == "<SSLContext(verify=True)>"93-94-89 def test_limits_repr():90 limits = httpx.Limits(max_connections=100)91 expected = (92 "Limits(max_connections=100, max_keepalive_connections=None,"88 unmodified lines181 182 def test_invalid_proxy_scheme():183 with pytest.raises(ValueError):184 httpx.Proxy("invalid://example.com")191-192-193-def test_certifi_lazy_loading():194- global httpx, certifi195- import sys196-197- del sys.modules["httpx"]198- del sys.modules["certifi"]199- del httpx200- del certifi201- import httpx202-203- assert "certifi" not in sys.modules204- _context = httpx.SSLContext()205- assert "certifi" in sys.modulesmodified:CHANGELOG.md+16 added-4 removed
4 unmodified lines5 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).6 7 ## [Unreleased]8 9-This release introduces an `httpx.SSLContext()` class and `ssl_context` parameter.9+The 0.28 release includes a limited set of backwards incompatible changes.10 11-* Added `httpx.SSLContext` class and `ssl_context` parameter. (#3022, #3335)12-* The `verify` and `cert` arguments have been deprecated and will now raise warnings. (#3022, #3335)11+**Backwards incompatible changes**:12+13+SSL configuration has been significantly simplified.14+15+* The `verify` argument no longer accepts string arguments.16+* The `cert` argument has now been removed.17+* The `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables are no longer automatically used.18+19+For users of the standard `verify=True` or `verify=False` cases this should require no changes.20+21+For information on configuring more complex SSL cases, please see the [SSL documentation](docs/advanced/ssl.md).22+23+**The following changes are also included**:24+25+* The undocumented `URL.raw` property has now been deprecated, and will raise warnings.26 * The deprecated `proxies` argument has now been removed.27 * The deprecated `app` argument has now been removed.15-* The `URL.raw` property has now been removed.28 * Ensure JSON request bodies are compact. (#3363)29 * Review URL percent escape sets, based on WHATWG spec. (#3371, #3373)30 * Ensure `certifi` and `httpcore` are only imported if required. (#3377)31 * Treat `socks5h` as a valid proxy scheme. (#3178)1096 unmodified lines