Skip to content
Myr

config.py

This file

Path

http3/config.py

241 lines · 7.7 KiB · Python

Last changed by

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

History of this file

Take it

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 1–7why, one step back
1import asyncio
2import os3import ssl4import typing56import certifi7

Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed

lines 8–9why, one step back
8from .__version__ import __version__
9

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 10why, one step back
10CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 11–13why, one step back
11VerifyTypes = typing.Union[str, bool]
12TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]13

Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed

lines 14–15why, one step back
14
15USER_AGENT = f"python-http3/{__version__}"

http3 (#86)Tom Christiebefore adoptionc9747aa

line 16why, one step back
16

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 17–36why, one step back
17DEFAULT_CIPHERS = ":".join(
18 [19 "ECDHE+AESGCM",20 "ECDHE+CHACHA20",21 "DHE+AESGCM",22 "DHE+CHACHA20",23 "ECDH+AESGCM",24 "DH+AESGCM",25 "ECDH+AES",26 "DH+AES",27 "RSA+AESGCM",28 "RSA+AES",29 "!aNULL",30 "!eNULL",31 "!MD5",32 "!DSS",33 ]34)3536

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 37–45why, one step back
37class SSLConfig:
38 """39 SSL Configuration.40 """4142 def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):43 self.cert = cert44 self.verify = verify45

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 46–47why, one step back
46 self.ssl_context: typing.Optional[ssl.SSLContext] = None
47

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 48–68why, one step back
48 def __eq__(self, other: typing.Any) -> bool:
49 return (50 isinstance(other, self.__class__)51 and self.cert == other.cert52 and self.verify == other.verify53 )5455 def __repr__(self) -> str:56 class_name = self.__class__.__name__57 return f"{class_name}(cert={self.cert}, verify={self.verify})"5859 def with_overrides(60 self, cert: CertTypes = None, verify: VerifyTypes = None61 ) -> "SSLConfig":62 cert = self.cert if cert is None else cert63 verify = self.verify if verify is None else verify64 if (cert == self.cert) and (verify == self.verify):65 return self66 return SSLConfig(cert=cert, verify=verify)6768 async def load_ssl_context(self) -> ssl.SSLContext:

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 69why, one step back
69 if self.ssl_context is None:

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 70–84why, one step back
70 if not self.verify:
71 self.ssl_context = self.load_ssl_context_no_verify()72 else:73 # Run the SSL loading in a threadpool, since it makes disk accesses.74 loop = asyncio.get_event_loop()75 self.ssl_context = await loop.run_in_executor(76 None, self.load_ssl_context_verify77 )7879 return self.ssl_context8081 def load_ssl_context_no_verify(self) -> ssl.SSLContext:82 """83 Return an SSL context for unverified connections.84 """

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 85–87why, one step back
85 context = self._create_default_ssl_context()
86 context.verify_mode = ssl.CERT_NONE87 context.check_hostname = False

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 88–103why, one step back
88 return context
8990 def load_ssl_context_verify(self) -> ssl.SSLContext:91 """92 Return an SSL context for verified connections.93 """94 if isinstance(self.verify, bool):95 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH96 elif os.path.exists(self.verify):97 ca_bundle_path = self.verify98 else:99 raise IOError(100 "Could not find a suitable TLS CA certificate bundle, "101 "invalid path: {}".format(self.verify)102 )103

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 104why, one step back
104 context = self._create_default_ssl_context()

http3 (#86)Tom Christiebefore adoptionc9747aa

line 105why, one step back
105 context.verify_mode = ssl.CERT_REQUIRED

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 106why, one step back
106 context.check_hostname = True

http3 (#86)Tom Christiebefore adoptionc9747aa

line 107why, one step back
107

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 108–113why, one step back
108 # Signal to server support for PHA in TLS 1.3. Raises an
109 # AttributeError if only read-only access is implemented.110 try:111 context.post_handshake_auth = True112 except AttributeError:113 pass

http3 (#86)Tom Christiebefore adoptionc9747aa

line 114why, one step back
114

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 115–120why, one step back
115 # Disable using 'commonName' for SSLContext.check_hostname
116 # when the 'subjectAltName' extension isn't available.117 try:118 context.hostname_checks_common_name = False119 except AttributeError:120 pass

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 121–129why, one step back
121
122 if os.path.isfile(ca_bundle_path):123 context.load_verify_locations(cafile=ca_bundle_path)124 elif os.path.isdir(ca_bundle_path):125 context.load_verify_locations(capath=ca_bundle_path)126127 if self.cert is not None:128 if isinstance(self.cert, str):129 context.load_cert_chain(certfile=self.cert)

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 130why, one step back
130 elif isinstance(self.cert, tuple) and len(self.cert) == 2:

http3 (#86)Tom Christiebefore adoptionc9747aa

line 131why, one step back
131 context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 132–135why, one step back
132 else:
133 context.load_cert_chain(134 certfile=self.cert[0], keyfile=self.cert[1], password=self.cert[2]135 )

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 136–138why, one step back
136
137 return context138

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 139–148why, one step back
139 def _create_default_ssl_context(self) -> ssl.SSLContext:
140 """141 Creates the default SSLContext object that's used for both verified142 and unverified connections.143 """144 context = ssl.SSLContext(ssl.PROTOCOL_TLS)145 context.options |= ssl.OP_NO_SSLv2146 context.options |= ssl.OP_NO_SSLv3147 context.options |= ssl.OP_NO_COMPRESSION148 context.set_ciphers(DEFAULT_CIPHERS)

http3 (#86)Tom Christiebefore adoptionc9747aa

line 149why, one step back
149

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 150–157why, one step back
150 if ssl.HAS_ALPN:
151 context.set_alpn_protocols(["h2", "http/1.1"])152 if ssl.HAS_NPN:153 context.set_npn_protocols(["h2", "http/1.1"])154155 return context156157

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 158–202why, one step back
158class TimeoutConfig:
159 """160 Timeout values.161 """162163 def __init__(164 self,165 timeout: TimeoutTypes = None,166 *,167 connect_timeout: float = None,168 read_timeout: float = None,169 write_timeout: float = None,170 ):171 if timeout is None:172 self.connect_timeout = connect_timeout173 self.read_timeout = read_timeout174 self.write_timeout = write_timeout175 else:176 # Specified as a single timeout value177 assert connect_timeout is None178 assert read_timeout is None179 assert write_timeout is None180 if isinstance(timeout, TimeoutConfig):181 self.connect_timeout = timeout.connect_timeout182 self.read_timeout = timeout.read_timeout183 self.write_timeout = timeout.write_timeout184 elif isinstance(timeout, tuple):185 self.connect_timeout = timeout[0]186 self.read_timeout = timeout[1]187 self.write_timeout = timeout[2]188 else:189 self.connect_timeout = timeout190 self.read_timeout = timeout191 self.write_timeout = timeout192193 def __eq__(self, other: typing.Any) -> bool:194 return (195 isinstance(other, self.__class__)196 and self.connect_timeout == other.connect_timeout197 and self.read_timeout == other.read_timeout198 and self.write_timeout == other.write_timeout199 )200201 def __repr__(self) -> str:202 class_name = self.__class__.__name__

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 203why, one step back
203 if len({self.connect_timeout, self.read_timeout, self.write_timeout}) == 1:

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 204–241why, one step back
204 return f"{class_name}(timeout={self.connect_timeout})"
205 return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"206207208class PoolLimits:209 """210 Limits on the number of connections in a connection pool.211 """212213 def __init__(214 self,215 *,216 soft_limit: int = None,217 hard_limit: int = None,218 pool_timeout: float = None,219 ):220 self.soft_limit = soft_limit221 self.hard_limit = hard_limit222 self.pool_timeout = pool_timeout223224 def __eq__(self, other: typing.Any) -> bool:225 return (226 isinstance(other, self.__class__)227 and self.soft_limit == other.soft_limit228 and self.hard_limit == other.hard_limit229 and self.pool_timeout == other.pool_timeout230 )231232 def __repr__(self) -> str:233 class_name = self.__class__.__name__234 return f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"235236237DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)238DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)239DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)240DEFAULT_CA_BUNDLE_PATH = certifi.where()241DEFAULT_MAX_REDIRECTS = 20