Skip to content
Myr

config.py

This file

Path

httpcore/config.py

180 lines · 5.7 KiB · Python

Last changed by

Finessing interfaceTom Christiebefore adoptiond7619a9

History of this file

Take it

1import asyncio2import os3import ssl4import typing56import certifi789class SSLConfig:10    """11    SSL Configuration.12    """1314    def __init__(15        self,16        *,17        cert: typing.Union[None, str, typing.Tuple[str, str]] = None,18        verify: typing.Union[str, bool] = True,19    ):20        self.cert = cert21        self.verify = verify2223    def __eq__(self, other: typing.Any) -> bool:24        return (25            isinstance(other, self.__class__)26            and self.cert == other.cert27            and self.verify == other.verify28        )2930    def __repr__(self) -> str:31        class_name = self.__class__.__name__32        return f"{class_name}(cert={self.cert}, verify={self.verify})"3334    async def load_ssl_context(self) -> ssl.SSLContext:35        if not hasattr(self, "ssl_context"):36            if not self.verify:37                self.ssl_context = self.load_ssl_context_no_verify()38            else:39                # Run the SSL loading in a threadpool, since it makes disk accesses.40                loop = asyncio.get_event_loop()41                self.ssl_context = await loop.run_in_executor(42                    None, self.load_ssl_context_verify43                )4445        return self.ssl_context4647    def load_ssl_context_no_verify(self) -> ssl.SSLContext:48        """49        Return an SSL context for unverified connections.50        """51        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)52        context.options |= ssl.OP_NO_SSLv253        context.options |= ssl.OP_NO_SSLv354        context.options |= ssl.OP_NO_COMPRESSION55        context.set_default_verify_paths()56        return context5758    def load_ssl_context_verify(self) -> ssl.SSLContext:59        """60        Return an SSL context for verified connections.61        """62        if isinstance(self.verify, bool):63            ca_bundle_path = DEFAULT_CA_BUNDLE_PATH64        elif os.path.exists(self.verify):65            ca_bundle_path = self.verify66        else:67            raise IOError(68                "Could not find a suitable TLS CA certificate bundle, "69                "invalid path: {}".format(self.verify)70            )7172        context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)7374        context.verify_mode = ssl.CERT_REQUIRED7576        context.options |= ssl.OP_NO_SSLv277        context.options |= ssl.OP_NO_SSLv378        context.options |= ssl.OP_NO_COMPRESSION7980        # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST81        # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the82        # blacklist defined in this section allows only the AES GCM and ChaCha2083        # cipher suites with ephemeral key negotiation.84        context.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")8586        if ssl.HAS_ALPN:87            context.set_alpn_protocols(["h2", "http/1.1"])88        if ssl.HAS_NPN:89            context.set_npn_protocols(["h2", "http/1.1"])9091        if os.path.isfile(ca_bundle_path):92            context.load_verify_locations(cafile=ca_bundle_path)93        elif os.path.isdir(ca_bundle_path):94            context.load_verify_locations(capath=ca_bundle_path)9596        if self.cert is not None:97            if isinstance(self.cert, str):98                context.load_cert_chain(certfile=self.cert)99            else:100                context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])101102        return context103104105class TimeoutConfig:106    """107    Timeout values.108    """109110    def __init__(111        self,112        timeout: float = None,113        *,114        connect_timeout: float = None,115        read_timeout: float = None,116        write_timeout: float = None,117    ):118        if timeout is not None:119            # Specified as a single timeout value120            assert connect_timeout is None121            assert read_timeout is None122            assert write_timeout is None123            connect_timeout = timeout124            read_timeout = timeout125            write_timeout = timeout126127        self.timeout = timeout128        self.connect_timeout = connect_timeout129        self.read_timeout = read_timeout130        self.write_timeout = write_timeout131132    def __eq__(self, other: typing.Any) -> bool:133        return (134            isinstance(other, self.__class__)135            and self.connect_timeout == other.connect_timeout136            and self.read_timeout == other.read_timeout137            and self.write_timeout == other.write_timeout138        )139140    def __repr__(self) -> str:141        class_name = self.__class__.__name__142        if self.timeout is not None:143            return f"{class_name}(timeout={self.timeout})"144        return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"145146147class PoolLimits:148    """149    Limits on the number of connections in a connection pool.150    """151152    def __init__(153        self,154        *,155        soft_limit: int = None,156        hard_limit: int = None,157        pool_timeout: float = None,158    ):159        self.soft_limit = soft_limit160        self.hard_limit = hard_limit161        self.pool_timeout = pool_timeout162163    def __eq__(self, other: typing.Any) -> bool:164        return (165            isinstance(other, self.__class__)166            and self.soft_limit == other.soft_limit167            and self.hard_limit == other.hard_limit168            and self.pool_timeout == other.pool_timeout169        )170171    def __repr__(self) -> str:172        class_name = self.__class__.__name__173        return f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"174175176DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)177DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)178DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)179DEFAULT_CA_BUNDLE_PATH = certifi.where()180DEFAULT_MAX_REDIRECTS = 20