Add support for SSL_CERT_FILE and SSL_CERT_DIR (#307)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Can Sarıgöl · committed by Seth Michael Larson · parent 1b82a2a · Browse files · 5 files·+118 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+118 added−0 removed
- tests:+64 added−0 removed
- other:+54 added−0 removed
Provenance
- Commit
c9810a7- Tree
fc36d60- Author
Can Sarıgöl <cansarigol@derinbilgi.com.tr>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
1b82a2a
5 files changed+118 added−0 removed
modified:docs/environment_variables.md+36 added
123456789101112131470 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211229 unmodified linesEnvironment Variables=====================
The HTTPX library can be configured via environment variables.Environment variables are used by default. To ignore environment variables, `trust_env` has to be set `False`.There are two ways to set `trust_env` to disable environment variables:
* On the client via `httpx.Client(trust_env=False)`* Per request via `client.get("<url>", trust_env=False)`
Here is a list of environment variables that HTTPX recognizesand what function they serve:
`HTTPX_DEBUG`70 unmodified linesCLIENT_HANDSHAKE_TRAFFIC_SECRET XXXXCLIENT_TRAFFIC_SECRET_0 XXXX```
`SSL_CERT_FILE`-----------
Valid values: a filename
if this environment variable is set then HTTPX will loadCA certificate from the specified file instead of the defaultlocation.
Example:
```consoleSSL_CERT_FILE=/path/to/ca-certs/ca-bundle.crt python -c "import httpx; httpx.get('https://example.com')"```
`SSL_CERT_DIR`-----------
Valid values: a directory
if this environment variable is set then HTTPX will loadCA certificates from the specified location instead of the defaultlocation.
Example:
```consoleSSL_CERT_DIR=/path/to/ca-certs/ python -c "import httpx; httpx.get('https://example.com')"```
`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`----------------------------------------
Valid values: A URL to a proxy9 unmodified linesmodified:httpx/config.py+6 added
4 unmodified lines5 6 import certifi7 8 from .__version__ import __version__9+from .utils import get_ca_bundle_from_env10 11 CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]12 VerifyTypes = typing.Union[str, bool, ssl.SSLContext]13 TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]103 unmodified lines117 ) -> ssl.SSLContext:118 """119 Return an SSL context for verified connections.120 """121+ if self.trust_env and self.verify is True:122+ ca_bundle = get_ca_bundle_from_env()123+ if ca_bundle is not None:124+ self.verify = ca_bundle # type: ignore125+126 if isinstance(self.verify, bool):127 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH128 elif Path(self.verify).exists():129 ca_bundle_path = Path(self.verify)211 unmodified linesmodified:httpx/utils.py+12 added
109 unmodified lines110 netrc_info = netrc.netrc(str(netrc_path))111 return netrc_info.authenticators(host) # type: ignore112 113 114+def get_ca_bundle_from_env() -> typing.Optional[str]:115+ if "SSL_CERT_FILE" in os.environ:116+ ssl_file = Path(os.environ["SSL_CERT_FILE"])117+ if ssl_file.is_file():118+ return str(ssl_file)119+ if "SSL_CERT_DIR" in os.environ:120+ ssl_path = Path(os.environ["SSL_CERT_DIR"])121+ if ssl_path.is_dir():122+ return str(ssl_path)123+ return None124+125+126 def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:127 """128 Returns a list of parsed link headers, for more info see:129 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link126 unmodified linesmodified:tests/test_config.py+27 added
1+import os2+import socket3 import ssl4 import sys5+from pathlib import Path6 7 import pytest8 9 import httpx18 unmodified lines28 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED29 assert context.check_hostname is True30 31 32+@pytest.mark.parametrize("config", ("SSL_CERT_FILE", "SSL_CERT_DIR"))33+def test_load_ssl_config_verify_env_file(https_server, ca_cert_pem_file, config):34+ os.environ[config] = (35+ ca_cert_pem_file36+ if config.endswith("_FILE")37+ else str(Path(ca_cert_pem_file).parent)38+ )39+ ssl_config = httpx.SSLConfig(trust_env=True)40+ context = ssl_config.load_ssl_context()41+ assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED42+ assert context.check_hostname is True43+ assert ssl_config.verify == os.environ[config]44+45+ # Skipping 'SSL_CERT_DIR' functional test for now because46+ # we're unable to get the certificate within the directory to47+ # load into the SSLContext. :(48+ if config == "SSL_CERT_FILE":49+ host = https_server.url.host50+ port = https_server.url.port51+ conn = socket.create_connection((host, port))52+ context.wrap_socket(conn, server_hostname=host)53+ assert len(context.get_ca_certs()) == 154+55+56 def test_load_ssl_config_verify_directory():57 path = httpx.config.DEFAULT_CA_BUNDLE_PATH.parent58 ssl_config = httpx.SSLConfig(verify=path)59 context = ssl_config.load_ssl_context()172 unmodified linesmodified:tests/test_utils.py+37 added
6 unmodified lines7 import httpx8 from httpx import utils9 from httpx.utils import (10 ElapsedTimer,11+ get_ca_bundle_from_env,12 get_environment_proxies,13 get_netrc_login,14 guess_json_utf,15 parse_header_links,104 unmodified lines120 # Reset the logger so we don't have verbose output in all unit tests121 logging.getLogger("httpx").handlers = []122 123 124+def test_get_ssl_cert_file():125+ # Two environments is not set.126+ assert get_ca_bundle_from_env() is None127+128+ os.environ["SSL_CERT_DIR"] = "tests/"129+ # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.130+ assert get_ca_bundle_from_env() == "tests"131+132+ del os.environ["SSL_CERT_DIR"]133+ os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"134+ # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.135+ assert get_ca_bundle_from_env() == "tests/test_utils.py"136+137+ os.environ["SSL_CERT_FILE"] = "wrongfile"138+ # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.139+ assert get_ca_bundle_from_env() is None140+141+ del os.environ["SSL_CERT_FILE"]142+ os.environ["SSL_CERT_DIR"] = "wrongpath"143+ # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.144+ assert get_ca_bundle_from_env() is None145+146+ os.environ["SSL_CERT_DIR"] = "tests/"147+ os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"148+ # Two environments is correctly set.149+ assert get_ca_bundle_from_env() == "tests/test_utils.py"150+151+ os.environ["SSL_CERT_FILE"] = "wrongfile"152+ # Two environments is set but SSL_CERT_FILE is not a file.153+ assert get_ca_bundle_from_env() == "tests"154+155+ os.environ["SSL_CERT_DIR"] = "wrongpath"156+ # Two environments is set but both are not correct.157+ assert get_ca_bundle_from_env() is None158+159+160 @pytest.mark.asyncio161 async def test_elapsed_timer():162 with ElapsedTimer() as timer:163 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)31 unmodified lines