Skip to content
Myr

config.py

This file

Path

httpcore/config.py

188 lines · 5.9 KiB · Python

Last changed by

First pass at HTTP/2 supportTom Christiebefore adoption53f3dc4

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 __hash__(self) -> int:31        as_tuple = (self.cert, self.verify)32        return hash(as_tuple)3334    def __repr__(self) -> str:35        class_name = self.__class__.__name__36        return f"{class_name}(cert={self.cert}, verify={self.verify})"3738    async def load_ssl_context(self) -> ssl.SSLContext:39        if not hasattr(self, "ssl_context"):40            if not self.verify:41                self.ssl_context = self.load_ssl_context_no_verify()42            else:43                # Run the SSL loading in a threadpool, since it makes disk accesses.44                loop = asyncio.get_event_loop()45                self.ssl_context = await loop.run_in_executor(46                    None, self.load_ssl_context_verify47                )4849        return self.ssl_context5051    def load_ssl_context_no_verify(self) -> ssl.SSLContext:52        """53        Return an SSL context for unverified connections.54        """55        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)56        context.options |= ssl.OP_NO_SSLv257        context.options |= ssl.OP_NO_SSLv358        context.options |= ssl.OP_NO_COMPRESSION59        context.set_default_verify_paths()60        return context6162    def load_ssl_context_verify(self) -> ssl.SSLContext:63        """64        Return an SSL context for verified connections.65        """66        if isinstance(self.verify, bool):67            ca_bundle_path = DEFAULT_CA_BUNDLE_PATH68        elif os.path.exists(self.verify):69            ca_bundle_path = self.verify70        else:71            raise IOError(72                "Could not find a suitable TLS CA certificate bundle, "73                "invalid path: {}".format(self.verify)74            )7576        context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)7778        context.options |= ssl.OP_NO_SSLv279        context.options |= ssl.OP_NO_SSLv380        context.options |= ssl.OP_NO_COMPRESSION8182        # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST83        # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the84        # blacklist defined in this section allows only the AES GCM and ChaCha2085        # cipher suites with ephemeral key negotiation.86        context.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")8788        if ssl.HAS_ALPN:89            context.set_alpn_protocols(["h2", "http/1.1"])90        if ssl.HAS_NPN:91            context.set_npn_protocols(["h2", "http/1.1"])9293        if os.path.isfile(ca_bundle_path):94            context.load_verify_locations(cafile=ca_bundle_path)95        elif os.path.isdir(ca_bundle_path):96            context.load_verify_locations(capath=ca_bundle_path)9798        if self.cert is not None:99            if isinstance(self.cert, str):100                context.load_cert_chain(certfile=self.cert)101            else:102                context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])103104        return context105106107class TimeoutConfig:108    """109    Timeout values.110    """111112    def __init__(113        self,114        timeout: float = None,115        *,116        connect_timeout: float = None,117        read_timeout: float = None,118        pool_timeout: float = None,119    ):120        if timeout is not None:121            # Specified as a single timeout value122            assert connect_timeout is None123            assert read_timeout is None124            assert pool_timeout is None125            connect_timeout = timeout126            read_timeout = timeout127            pool_timeout = timeout128129        self.timeout = timeout130        self.connect_timeout = connect_timeout131        self.read_timeout = read_timeout132        self.pool_timeout = pool_timeout133134    def __eq__(self, other: typing.Any) -> bool:135        return (136            isinstance(other, self.__class__)137            and self.connect_timeout == other.connect_timeout138            and self.read_timeout == other.read_timeout139            and self.pool_timeout == other.pool_timeout140        )141142    def __hash__(self) -> int:143        as_tuple = (self.connect_timeout, self.read_timeout, self.pool_timeout)144        return hash(as_tuple)145146    def __repr__(self) -> str:147        class_name = self.__class__.__name__148        if self.timeout is not None:149            return f"{class_name}(timeout={self.timeout})"150        return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, pool_timeout={self.pool_timeout})"151152153class PoolLimits:154    """155    Limits on the number of connections in a connection pool.156    """157158    def __init__(159        self,160        *,161        soft_limit: typing.Optional[int] = None,162        hard_limit: typing.Optional[int] = None,163    ):164        self.soft_limit = soft_limit165        self.hard_limit = hard_limit166167    def __eq__(self, other: typing.Any) -> bool:168        return (169            isinstance(other, self.__class__)170            and self.soft_limit == other.soft_limit171            and self.hard_limit == other.hard_limit172        )173174    def __hash__(self) -> int:175        as_tuple = (self.soft_limit, self.hard_limit)176        return hash(as_tuple)177178    def __repr__(self) -> str:179        class_name = self.__class__.__name__180        return (181            f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"182        )183184185DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)186DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)187DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)188DEFAULT_CA_BUNDLE_PATH = certifi.where()