Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 0f9adc9

Browse files
authored
Add missing type hints to synapse.crypto. (#11146)
And require type hints for this module.
1 parent 09eff1b commit 0f9adc9

File tree

5 files changed

+36
-18
lines changed

5 files changed

+36
-18
lines changed

changelog.d/11146.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add missing type hints to `synapse.crypto`.

mypy.ini

+3
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ files =
103103
[mypy-synapse.api.*]
104104
disallow_untyped_defs = True
105105

106+
[mypy-synapse.crypto.*]
107+
disallow_untyped_defs = True
108+
106109
[mypy-synapse.events.*]
107110
disallow_untyped_defs = True
108111

synapse/crypto/context_factory.py

+26-14
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,12 @@
2929
TLSVersion,
3030
platformTrust,
3131
)
32+
from twisted.protocols.tls import TLSMemoryBIOProtocol
3233
from twisted.python.failure import Failure
3334
from twisted.web.iweb import IPolicyForHTTPS
3435

36+
from synapse.config.homeserver import HomeServerConfig
37+
3538
logger = logging.getLogger(__name__)
3639

3740

@@ -51,7 +54,7 @@ class ServerContextFactory(ContextFactory):
5154
per https://github.com/matrix-org/synapse/issues/1691
5255
"""
5356

54-
def __init__(self, config):
57+
def __init__(self, config: HomeServerConfig):
5558
# TODO: once pyOpenSSL exposes TLS_METHOD and SSL_CTX_set_min_proto_version,
5659
# switch to those (see https://github.com/pyca/cryptography/issues/5379).
5760
#
@@ -64,7 +67,7 @@ def __init__(self, config):
6467
self.configure_context(self._context, config)
6568

6669
@staticmethod
67-
def configure_context(context, config):
70+
def configure_context(context: SSL.Context, config: HomeServerConfig) -> None:
6871
try:
6972
_ecCurve = crypto.get_elliptic_curve(_defaultCurveName)
7073
context.set_tmp_ecdh(_ecCurve)
@@ -75,14 +78,15 @@ def configure_context(context, config):
7578
SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3 | SSL.OP_NO_TLSv1 | SSL.OP_NO_TLSv1_1
7679
)
7780
context.use_certificate_chain_file(config.tls.tls_certificate_file)
81+
assert config.tls.tls_private_key is not None
7882
context.use_privatekey(config.tls.tls_private_key)
7983

8084
# https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
8185
context.set_cipher_list(
82-
"ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES256:ECDH+AES128:!aNULL:!SHA1:!AESCCM"
86+
b"ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES256:ECDH+AES128:!aNULL:!SHA1:!AESCCM"
8387
)
8488

85-
def getContext(self):
89+
def getContext(self) -> SSL.Context:
8690
return self._context
8791

8892

@@ -98,7 +102,7 @@ class FederationPolicyForHTTPS:
98102
constructs an SSLClientConnectionCreator factory accordingly.
99103
"""
100104

101-
def __init__(self, config):
105+
def __init__(self, config: HomeServerConfig):
102106
self._config = config
103107

104108
# Check if we're using a custom list of a CA certificates
@@ -131,7 +135,7 @@ def __init__(self, config):
131135
self._config.tls.federation_certificate_verification_whitelist
132136
)
133137

134-
def get_options(self, host: bytes):
138+
def get_options(self, host: bytes) -> IOpenSSLClientConnectionCreator:
135139
# IPolicyForHTTPS.get_options takes bytes, but we want to compare
136140
# against the str whitelist. The hostnames in the whitelist are already
137141
# IDNA-encoded like the hosts will be here.
@@ -153,7 +157,9 @@ def get_options(self, host: bytes):
153157

154158
return SSLClientConnectionCreator(host, ssl_context, should_verify)
155159

156-
def creatorForNetloc(self, hostname, port):
160+
def creatorForNetloc(
161+
self, hostname: bytes, port: int
162+
) -> IOpenSSLClientConnectionCreator:
157163
"""Implements the IPolicyForHTTPS interface so that this can be passed
158164
directly to agents.
159165
"""
@@ -169,16 +175,18 @@ class RegularPolicyForHTTPS:
169175
trust root.
170176
"""
171177

172-
def __init__(self):
178+
def __init__(self) -> None:
173179
trust_root = platformTrust()
174180
self._ssl_context = CertificateOptions(trustRoot=trust_root).getContext()
175181
self._ssl_context.set_info_callback(_context_info_cb)
176182

177-
def creatorForNetloc(self, hostname, port):
183+
def creatorForNetloc(
184+
self, hostname: bytes, port: int
185+
) -> IOpenSSLClientConnectionCreator:
178186
return SSLClientConnectionCreator(hostname, self._ssl_context, True)
179187

180188

181-
def _context_info_cb(ssl_connection, where, ret):
189+
def _context_info_cb(ssl_connection: SSL.Connection, where: int, ret: int) -> None:
182190
"""The 'information callback' for our openssl context objects.
183191
184192
Note: Once this is set as the info callback on a Context object, the Context should
@@ -204,11 +212,13 @@ class SSLClientConnectionCreator:
204212
Replaces twisted.internet.ssl.ClientTLSOptions
205213
"""
206214

207-
def __init__(self, hostname: bytes, ctx, verify_certs: bool):
215+
def __init__(self, hostname: bytes, ctx: SSL.Context, verify_certs: bool):
208216
self._ctx = ctx
209217
self._verifier = ConnectionVerifier(hostname, verify_certs)
210218

211-
def clientConnectionForTLS(self, tls_protocol):
219+
def clientConnectionForTLS(
220+
self, tls_protocol: TLSMemoryBIOProtocol
221+
) -> SSL.Connection:
212222
context = self._ctx
213223
connection = SSL.Connection(context, None)
214224

@@ -219,7 +229,7 @@ def clientConnectionForTLS(self, tls_protocol):
219229
# ... and we also gut-wrench a '_synapse_tls_verifier' attribute into the
220230
# tls_protocol so that the SSL context's info callback has something to
221231
# call to do the cert verification.
222-
tls_protocol._synapse_tls_verifier = self._verifier
232+
tls_protocol._synapse_tls_verifier = self._verifier # type: ignore[attr-defined]
223233
return connection
224234

225235

@@ -244,7 +254,9 @@ def __init__(self, hostname: bytes, verify_certs: bool):
244254
self._hostnameBytes = hostname
245255
self._hostnameASCII = self._hostnameBytes.decode("ascii")
246256

247-
def verify_context_info_cb(self, ssl_connection, where):
257+
def verify_context_info_cb(
258+
self, ssl_connection: SSL.Connection, where: int
259+
) -> None:
248260
if where & SSL.SSL_CB_HANDSHAKE_START and not self._is_ip_address:
249261
ssl_connection.set_tlsext_host_name(self._hostnameBytes)
250262

synapse/crypto/event_signing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def compute_content_hash(
100100

101101

102102
def compute_event_reference_hash(
103-
event, hash_algorithm: Hasher = hashlib.sha256
103+
event: EventBase, hash_algorithm: Hasher = hashlib.sha256
104104
) -> Tuple[str, bytes]:
105105
"""Computes the event reference hash. This is the hash of the redacted
106106
event.

synapse/crypto/keyring.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def from_json_object(
8787
server_name: str,
8888
json_object: JsonDict,
8989
minimum_valid_until_ms: int,
90-
):
90+
) -> "VerifyJsonRequest":
9191
"""Create a VerifyJsonRequest to verify all signatures on a signed JSON
9292
object for the given server.
9393
"""
@@ -104,7 +104,7 @@ def from_event(
104104
server_name: str,
105105
event: EventBase,
106106
minimum_valid_until_ms: int,
107-
):
107+
) -> "VerifyJsonRequest":
108108
"""Create a VerifyJsonRequest to verify all signatures on an event
109109
object for the given server.
110110
"""
@@ -449,7 +449,9 @@ def __init__(self, hs: "HomeServer"):
449449

450450
self.store = hs.get_datastore()
451451

452-
async def _fetch_keys(self, keys_to_fetch: List[_FetchKeyRequest]):
452+
async def _fetch_keys(
453+
self, keys_to_fetch: List[_FetchKeyRequest]
454+
) -> Dict[str, Dict[str, FetchKeyResult]]:
453455
key_ids_to_fetch = (
454456
(queue_value.server_name, key_id)
455457
for queue_value in keys_to_fetch

0 commit comments

Comments
 (0)