Skip to content
Myr

config.py

This file

Path

httpx/config.py

336 lines · 11.0 KiB · Python

Last changed by

Add support for SSLKEYLOGFILE (#301)Tomás Faríasbefore adoptiondb7f2d0

History of this file

Take it

1import os2import ssl3import typing4from pathlib import Path56import certifi78from .__version__ import __version__910CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]11VerifyTypes = typing.Union[str, bool, ssl.SSLContext]12TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]13HTTPVersionTypes = typing.Union[14    str, typing.List[str], typing.Tuple[str], "HTTPVersionConfig"15]161718USER_AGENT = f"python-httpx/{__version__}"1920HTTP_VERSIONS_TO_ALPN_IDENTIFIERS = {"HTTP/1.1": "http/1.1", "HTTP/2": "h2"}2122DEFAULT_CIPHERS = ":".join(23    [24        "ECDHE+AESGCM",25        "ECDHE+CHACHA20",26        "DHE+AESGCM",27        "DHE+CHACHA20",28        "ECDH+AESGCM",29        "DH+AESGCM",30        "ECDH+AES",31        "DH+AES",32        "RSA+AESGCM",33        "RSA+AES",34        "!aNULL",35        "!eNULL",36        "!MD5",37        "!DSS",38    ]39)404142class SSLConfig:43    """44    SSL Configuration.45    """4647    def __init__(48        self,49        *,50        cert: CertTypes = None,51        verify: VerifyTypes = True,52        trust_env: bool = None,53    ):54        self.cert = cert5556        # Allow passing in our own SSLContext object that's pre-configured.57        # If you do this we assume that you want verify=True as well.58        ssl_context = None59        if isinstance(verify, ssl.SSLContext):60            ssl_context = verify61            verify = True62            self._load_client_certs(ssl_context)6364        self.ssl_context: typing.Optional[ssl.SSLContext] = ssl_context65        self.verify: typing.Union[str, bool] = verify66        self.trust_env = trust_env6768    def __eq__(self, other: typing.Any) -> bool:69        return (70            isinstance(other, self.__class__)71            and self.cert == other.cert72            and self.verify == other.verify73        )7475    def __repr__(self) -> str:76        class_name = self.__class__.__name__77        return f"{class_name}(cert={self.cert}, verify={self.verify})"7879    def with_overrides(80        self, cert: CertTypes = None, verify: VerifyTypes = None81    ) -> "SSLConfig":82        cert = self.cert if cert is None else cert83        verify = self.verify if verify is None else verify84        if (cert == self.cert) and (verify == self.verify):85            return self86        return SSLConfig(cert=cert, verify=verify)8788    def load_ssl_context(89        self, http_versions: "HTTPVersionConfig" = None90    ) -> ssl.SSLContext:91        http_versions = HTTPVersionConfig() if http_versions is None else http_versions9293        if self.ssl_context is None:94            self.ssl_context = (95                self.load_ssl_context_verify(http_versions=http_versions)96                if self.verify97                else self.load_ssl_context_no_verify(http_versions=http_versions)98            )99100        assert self.ssl_context is not None101        return self.ssl_context102103    def load_ssl_context_no_verify(104        self, http_versions: "HTTPVersionConfig"105    ) -> ssl.SSLContext:106        """107        Return an SSL context for unverified connections.108        """109        context = self._create_default_ssl_context(http_versions=http_versions)110        context.verify_mode = ssl.CERT_NONE111        context.check_hostname = False112        return context113114    def load_ssl_context_verify(115        self, http_versions: "HTTPVersionConfig"116    ) -> ssl.SSLContext:117        """118        Return an SSL context for verified connections.119        """120        if isinstance(self.verify, bool):121            ca_bundle_path = DEFAULT_CA_BUNDLE_PATH122        elif Path(self.verify).exists():123            ca_bundle_path = Path(self.verify)124        else:125            raise IOError(126                "Could not find a suitable TLS CA certificate bundle, "127                "invalid path: {}".format(self.verify)128            )129130        context = self._create_default_ssl_context(http_versions=http_versions)131        context.verify_mode = ssl.CERT_REQUIRED132        context.check_hostname = True133134        # Signal to server support for PHA in TLS 1.3. Raises an135        # AttributeError if only read-only access is implemented.136        try:137            context.post_handshake_auth = True  # type: ignore138        except AttributeError:  # pragma: nocover139            pass140141        # Disable using 'commonName' for SSLContext.check_hostname142        # when the 'subjectAltName' extension isn't available.143        try:144            context.hostname_checks_common_name = False  # type: ignore145        except AttributeError:  # pragma: nocover146            pass147148        if ca_bundle_path.is_file():149            context.load_verify_locations(cafile=str(ca_bundle_path))150        elif ca_bundle_path.is_dir():151            context.load_verify_locations(capath=str(ca_bundle_path))152153        self._load_client_certs(context)154155        return context156157    def _create_default_ssl_context(158        self, http_versions: "HTTPVersionConfig"159    ) -> ssl.SSLContext:160        """161        Creates the default SSLContext object that's used for both verified162        and unverified connections.163        """164        context = ssl.SSLContext(ssl.PROTOCOL_TLS)165        context.options |= ssl.OP_NO_SSLv2166        context.options |= ssl.OP_NO_SSLv3167        context.options |= ssl.OP_NO_TLSv1168        context.options |= ssl.OP_NO_TLSv1_1169        context.options |= ssl.OP_NO_COMPRESSION170        context.set_ciphers(DEFAULT_CIPHERS)171172        if ssl.HAS_ALPN:173            context.set_alpn_protocols(http_versions.alpn_identifiers)174        if ssl.HAS_NPN:  # pragma: no cover175            context.set_npn_protocols(http_versions.alpn_identifiers)176177        if hasattr(context, "keylog_filename"):178            keylogfile = os.environ.get("SSLKEYLOGFILE")179            if keylogfile and self.trust_env:180                context.keylog_filename = keylogfile  # type: ignore181182        return context183184    def _load_client_certs(self, ssl_context: ssl.SSLContext) -> None:185        """186        Loads client certificates into our SSLContext object187        """188        if self.cert is not None:189            if isinstance(self.cert, str):190                ssl_context.load_cert_chain(certfile=self.cert)191            elif isinstance(self.cert, tuple) and len(self.cert) == 2:192                ssl_context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])193            elif isinstance(self.cert, tuple) and len(self.cert) == 3:194                ssl_context.load_cert_chain(195                    certfile=self.cert[0],196                    keyfile=self.cert[1],197                    password=self.cert[2],  # type: ignore198                )199200201class TimeoutConfig:202    """203    Timeout values.204    """205206    def __init__(207        self,208        timeout: TimeoutTypes = None,209        *,210        connect_timeout: float = None,211        read_timeout: float = None,212        write_timeout: float = None,213    ):214        if timeout is None:215            self.connect_timeout = connect_timeout216            self.read_timeout = read_timeout217            self.write_timeout = write_timeout218        else:219            # Specified as a single timeout value220            assert connect_timeout is None221            assert read_timeout is None222            assert write_timeout is None223            if isinstance(timeout, TimeoutConfig):224                self.connect_timeout = timeout.connect_timeout225                self.read_timeout = timeout.read_timeout226                self.write_timeout = timeout.write_timeout227            elif isinstance(timeout, tuple):228                self.connect_timeout = timeout[0]229                self.read_timeout = timeout[1]230                self.write_timeout = timeout[2]231            else:232                self.connect_timeout = timeout233                self.read_timeout = timeout234                self.write_timeout = timeout235236    def __eq__(self, other: typing.Any) -> bool:237        return (238            isinstance(other, self.__class__)239            and self.connect_timeout == other.connect_timeout240            and self.read_timeout == other.read_timeout241            and self.write_timeout == other.write_timeout242        )243244    def __repr__(self) -> str:245        class_name = self.__class__.__name__246        if len({self.connect_timeout, self.read_timeout, self.write_timeout}) == 1:247            return f"{class_name}(timeout={self.connect_timeout})"248        return (249            f"{class_name}(connect_timeout={self.connect_timeout}, "250            f"read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"251        )252253254class HTTPVersionConfig:255    """256    Configure which HTTP protocol versions are supported.257    """258259    def __init__(self, http_versions: HTTPVersionTypes = None):260        if http_versions is None:261            http_versions = ["HTTP/1.1", "HTTP/2"]262263        if isinstance(http_versions, str):264            self.http_versions = {http_versions.upper()}265        elif isinstance(http_versions, HTTPVersionConfig):266            self.http_versions = http_versions.http_versions267        elif isinstance(http_versions, typing.Iterable):268            self.http_versions = {269                version.upper() if isinstance(version, str) else version270                for version in http_versions271            }272        else:273            raise TypeError(274                f"HTTP version should be a string or list of strings, "275                "but got {type(http_versions)}"276            )277278        for version in self.http_versions:279            if version not in ("HTTP/1.1", "HTTP/2"):280                raise ValueError(f"Unsupported HTTP version {version!r}.")281282        if not self.http_versions:283            raise ValueError(f"HTTP versions cannot be an empty list.")284285    @property286    def alpn_identifiers(self) -> typing.List[str]:287        """288        Returns a list of supported ALPN identifiers. (One or more of "http/1.1", "h2").289        """290        return [291            HTTP_VERSIONS_TO_ALPN_IDENTIFIERS[version] for version in self.http_versions292        ]293294    def __repr__(self) -> str:295        class_name = self.__class__.__name__296        value = sorted(list(self.http_versions))297        return f"{class_name}({value!r})"298299300class PoolLimits:301    """302    Limits on the number of connections in a connection pool.303    """304305    def __init__(306        self,307        *,308        soft_limit: int = None,309        hard_limit: int = None,310        pool_timeout: float = None,311    ):312        self.soft_limit = soft_limit313        self.hard_limit = hard_limit314        self.pool_timeout = pool_timeout315316    def __eq__(self, other: typing.Any) -> bool:317        return (318            isinstance(other, self.__class__)319            and self.soft_limit == other.soft_limit320            and self.hard_limit == other.hard_limit321            and self.pool_timeout == other.pool_timeout322        )323324    def __repr__(self) -> str:325        class_name = self.__class__.__name__326        return (327            f"{class_name}(soft_limit={self.soft_limit}, "328            f"hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"329        )330331332DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)333DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)334DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)335DEFAULT_CA_BUNDLE_PATH = Path(certifi.where())336DEFAULT_MAX_REDIRECTS = 20