Skip to content
Myr

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

5 files+118 added−0 removed

modified:docs/environment_variables.md+36 added
modified:httpx/config.py+6 added
4 unmodified lines
56import certifi78from .__version__ import __version__9from .utils import get_ca_bundle_from_env1011CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]12VerifyTypes = typing.Union[str, bool, ssl.SSLContext]13TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]
103 unmodified lines
117 ) -> 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: ignore125126 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 lines
modified:httpx/utils.py+12 added
109 unmodified lines
110 netrc_info = netrc.netrc(str(netrc_path))111 return netrc_info.authenticators(host) # type: ignore112113114def 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 None124125126def 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/Link
126 unmodified lines
modified:tests/test_config.py+27 added
1import os2import socket3import ssl4import sys5from pathlib import Path67import pytest89import httpx
18 unmodified lines
28 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED29 assert context.check_hostname is True303132@pytest.mark.parametrize("config", ("SSL_CERT_FILE", "SSL_CERT_DIR"))33def 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]4445 # 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()) == 1545556def 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 lines
modified:tests/test_utils.py+37 added
6 unmodified lines
7import httpx8from httpx import utils9from 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 lines
120 # Reset the logger so we don't have verbose output in all unit tests121 logging.getLogger("httpx").handlers = []122123124def test_get_ssl_cert_file():125 # Two environments is not set.126 assert get_ca_bundle_from_env() is None127128 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"131132 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"136137 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 None140141 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 None145146 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"150151 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"154155 os.environ["SSL_CERT_DIR"] = "wrongpath"156 # Two environments is set but both are not correct.157 assert get_ca_bundle_from_env() is None158159160@pytest.mark.asyncio161async def test_elapsed_timer():162 with ElapsedTimer() as timer:163 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)
31 unmodified lines