config.py
This file
Path
httpcore/config.py
196 lines · 6.7 KiB · Python
Last changed by
Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
History of this fileTake it
1import asyncio2import os3import ssl4import typing56import certifi78CertTypes = typing.Union[str, typing.Tuple[str, str]]9VerifyTypes = typing.Union[str, bool]10TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]111213class SSLConfig:14 """15 SSL Configuration.16 """1718 def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):19 self.cert = cert20 self.verify = verify2122 def __eq__(self, other: typing.Any) -> bool:23 return (24 isinstance(other, self.__class__)25 and self.cert == other.cert26 and self.verify == other.verify27 )2829 def __repr__(self) -> str:30 class_name = self.__class__.__name__31 return f"{class_name}(cert={self.cert}, verify={self.verify})"3233 def with_overrides(34 self, cert: CertTypes = None, verify: VerifyTypes = None35 ) -> "SSLConfig":36 cert = self.cert if cert is None else cert37 verify = self.verify if verify is None else verify38 if (cert == self.cert) and (verify == self.verify):39 return self40 return SSLConfig(cert=cert, verify=verify)4142 async def load_ssl_context(self) -> ssl.SSLContext:43 if not hasattr(self, "ssl_context"):44 if not self.verify:45 self.ssl_context = self.load_ssl_context_no_verify()46 else:47 # Run the SSL loading in a threadpool, since it makes disk accesses.48 loop = asyncio.get_event_loop()49 self.ssl_context = await loop.run_in_executor(50 None, self.load_ssl_context_verify51 )5253 return self.ssl_context5455 def load_ssl_context_no_verify(self) -> ssl.SSLContext:56 """57 Return an SSL context for unverified connections.58 """59 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)60 context.options |= ssl.OP_NO_SSLv261 context.options |= ssl.OP_NO_SSLv362 context.options |= ssl.OP_NO_COMPRESSION63 context.set_default_verify_paths()64 return context6566 def load_ssl_context_verify(self) -> ssl.SSLContext:67 """68 Return an SSL context for verified connections.69 """70 if isinstance(self.verify, bool):71 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH72 elif os.path.exists(self.verify):73 ca_bundle_path = self.verify74 else:75 raise IOError(76 "Could not find a suitable TLS CA certificate bundle, "77 "invalid path: {}".format(self.verify)78 )7980 context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)8182 context.verify_mode = ssl.CERT_REQUIRED8384 context.options |= ssl.OP_NO_SSLv285 context.options |= ssl.OP_NO_SSLv386 context.options |= ssl.OP_NO_COMPRESSION8788 # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST89 # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the90 # blacklist defined in this section allows only the AES GCM and ChaCha2091 # cipher suites with ephemeral key negotiation.92 context.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")9394 if ssl.HAS_ALPN:95 context.set_alpn_protocols(["h2", "http/1.1"])96 if ssl.HAS_NPN:97 context.set_npn_protocols(["h2", "http/1.1"])9899 if os.path.isfile(ca_bundle_path):100 context.load_verify_locations(cafile=ca_bundle_path)101 elif os.path.isdir(ca_bundle_path):102 context.load_verify_locations(capath=ca_bundle_path)103104 if self.cert is not None:105 if isinstance(self.cert, str):106 context.load_cert_chain(certfile=self.cert)107 else:108 context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])109110 return context111112113class TimeoutConfig:114 """115 Timeout values.116 """117118 def __init__(119 self,120 timeout: TimeoutTypes = None,121 *,122 connect_timeout: float = None,123 read_timeout: float = None,124 write_timeout: float = None,125 ):126 if timeout is None:127 self.connect_timeout = connect_timeout128 self.read_timeout = read_timeout129 self.write_timeout = write_timeout130 else:131 # Specified as a single timeout value132 assert connect_timeout is None133 assert read_timeout is None134 assert write_timeout is None135 if isinstance(timeout, TimeoutConfig):136 self.connect_timeout = timeout.connect_timeout137 self.read_timeout = timeout.read_timeout138 self.write_timeout = timeout.write_timeout139 elif isinstance(timeout, tuple):140 self.connect_timeout = timeout[0]141 self.read_timeout = timeout[1]142 self.write_timeout = timeout[2]143 else:144 self.connect_timeout = timeout145 self.read_timeout = timeout146 self.write_timeout = timeout147148 def __eq__(self, other: typing.Any) -> bool:149 return (150 isinstance(other, self.__class__)151 and self.connect_timeout == other.connect_timeout152 and self.read_timeout == other.read_timeout153 and self.write_timeout == other.write_timeout154 )155156 def __repr__(self) -> str:157 class_name = self.__class__.__name__158 if len(set([self.connect_timeout, self.read_timeout, self.write_timeout])) == 1:159 return f"{class_name}(timeout={self.connect_timeout})"160 return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"161162163class PoolLimits:164 """165 Limits on the number of connections in a connection pool.166 """167168 def __init__(169 self,170 *,171 soft_limit: int = None,172 hard_limit: int = None,173 pool_timeout: float = None,174 ):175 self.soft_limit = soft_limit176 self.hard_limit = hard_limit177 self.pool_timeout = pool_timeout178179 def __eq__(self, other: typing.Any) -> bool:180 return (181 isinstance(other, self.__class__)182 and self.soft_limit == other.soft_limit183 and self.hard_limit == other.hard_limit184 and self.pool_timeout == other.pool_timeout185 )186187 def __repr__(self) -> str:188 class_name = self.__class__.__name__189 return f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"190191192DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)193DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)194DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)195DEFAULT_CA_BUNDLE_PATH = certifi.where()196DEFAULT_MAX_REDIRECTS = 20