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

Commit 687d30b

Browse files
committed
Merge commit 'c9c544cda' into anoa/dinsic_release_1_21_x
* commit 'c9c544cda': Remove `ChainedIdGenerator`. (#8123) Switch the JSON byte producer from a pull to a push producer. (#8116) Updated docs: Added note about missing 308 redirect support. (#8120) Be stricter about JSON that is accepted by Synapse (#8106) Convert runWithConnection to async. (#8121) Remove the unused inlineCallbacks code-paths in the caching code (#8119) Separate `get_current_token` into two. (#8113) Convert events worker database to async/await. (#8071) Add a link to the matrix-synapse-rest-password-provider. (#8111)
2 parents 1e9ec2a + c9c544c commit 687d30b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+409
-419
lines changed

changelog.d/8071.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Convert various parts of the codebase to async/await.

changelog.d/8106.bugfix

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a long-standing bug where invalid JSON would be accepted by Synapse.

changelog.d/8111.doc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Link to matrix-synapse-rest-password-provider in the password provider documentation.

changelog.d/8113.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Separate `get_current_token` into two since there are two different use cases for it.

changelog.d/8116.feature

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Iteratively encode JSON to avoid blocking the reactor.

changelog.d/8119.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Convert various parts of the codebase to async/await.

changelog.d/8120.doc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Updated documentation to note that Synapse does not follow `HTTP 308` redirects due to an upstream library not supporting them. Contributed by Ryan Cole.

changelog.d/8121.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Convert various parts of the codebase to async/await.

changelog.d/8123.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Remove `ChainedIdGenerator`.

docs/federate.md

+12
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,18 @@ you invite them to. This can be caused by an incorrectly-configured reverse
4747
proxy: see [reverse_proxy.md](<reverse_proxy.md>) for instructions on how to correctly
4848
configure a reverse proxy.
4949

50+
### Known issues
51+
52+
**HTTP `308 Permanent Redirect` redirects are not followed**: Due to missing features
53+
in the HTTP library used by Synapse, 308 redirects are currently not followed by
54+
federating servers, which can cause `M_UNKNOWN` or `401 Unauthorized` errors. This
55+
may affect users who are redirecting apex-to-www (e.g. `example.com` -> `www.example.com`),
56+
and especially users of the Kubernetes *Nginx Ingress* module, which uses 308 redirect
57+
codes by default. For those Kubernetes users, [this Stackoverflow post](https://stackoverflow.com/a/52617528/5096871)
58+
might be helpful. For other users, switching to a `301 Moved Permanently` code may be
59+
an option. 308 redirect codes will be supported properly in a future
60+
release of Synapse.
61+
5062
## Running a demo federation of Synapses
5163

5264
If you want to get up and running quickly with a trio of homeservers in a

docs/password_auth_providers.md

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ password auth provider module implementations:
1414

1515
* [matrix-synapse-ldap3](https://github.com/matrix-org/matrix-synapse-ldap3/)
1616
* [matrix-synapse-shared-secret-auth](https://github.com/devture/matrix-synapse-shared-secret-auth)
17+
* [matrix-synapse-rest-password-provider](https://github.com/ma1uta/matrix-synapse-rest-password-provider)
1718

1819
## Required methods
1920

synapse/api/errors.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@
2222
from http import HTTPStatus
2323
from typing import Dict, List, Optional, Union
2424

25-
from canonicaljson import json
26-
2725
from twisted.web import http
2826

27+
from synapse.util import json_decoder
28+
2929
if typing.TYPE_CHECKING:
3030
from synapse.types import JsonDict
3131

@@ -594,7 +594,7 @@ def to_synapse_error(self):
594594
# try to parse the body as json, to get better errcode/msg, but
595595
# default to M_UNKNOWN with the HTTP status as the error text
596596
try:
597-
j = json.loads(self.response.decode("utf-8"))
597+
j = json_decoder.decode(self.response.decode("utf-8"))
598598
except ValueError:
599599
j = {}
600600

synapse/event_auth.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def check(
4747
Args:
4848
room_version_obj: the version of the room
4949
event: the event being checked.
50-
auth_events (dict: event-key -> event): the existing room state.
50+
auth_events: the existing room state.
5151
5252
Raises:
5353
AuthError if the checks fail

synapse/federation/federation_server.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
Union,
2929
)
3030

31-
from canonicaljson import json
3231
from prometheus_client import Counter, Histogram
3332

3433
from twisted.internet import defer
@@ -63,7 +62,7 @@
6362
ReplicationGetQueryRestServlet,
6463
)
6564
from synapse.types import JsonDict, get_domain_from_id
66-
from synapse.util import glob_to_regex, unwrapFirstError
65+
from synapse.util import glob_to_regex, json_decoder, unwrapFirstError
6766
from synapse.util.async_helpers import Linearizer, concurrently_execute
6867
from synapse.util.caches.response_cache import ResponseCache
6968

@@ -551,7 +550,7 @@ async def on_claim_client_keys(
551550
for device_id, keys in device_keys.items():
552551
for key_id, json_str in keys.items():
553552
json_result.setdefault(user_id, {})[device_id] = {
554-
key_id: json.loads(json_str)
553+
key_id: json_decoder.decode(json_str)
555554
}
556555

557556
logger.info(

synapse/federation/sender/transaction_manager.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@
1515
import logging
1616
from typing import TYPE_CHECKING, List, Tuple
1717

18-
from canonicaljson import json
19-
2018
from synapse.api.errors import HttpResponseException
2119
from synapse.events import EventBase
2220
from synapse.federation.persistence import TransactionActions
@@ -28,6 +26,7 @@
2826
tags,
2927
whitelisted_homeserver,
3028
)
29+
from synapse.util import json_decoder
3130
from synapse.util.metrics import measure_func
3231

3332
if TYPE_CHECKING:
@@ -71,7 +70,7 @@ async def send_new_transaction(
7170
for edu in pending_edus:
7271
context = edu.get_context()
7372
if context:
74-
span_contexts.append(extract_text_map(json.loads(context)))
73+
span_contexts.append(extract_text_map(json_decoder.decode(context)))
7574
if keep_destination:
7675
edu.strip_context()
7776

synapse/handlers/e2e_keys.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from typing import Dict, List, Optional, Tuple
2020

2121
import attr
22-
from canonicaljson import encode_canonical_json, json
22+
from canonicaljson import encode_canonical_json
2323
from signedjson.key import VerifyKey, decode_verify_key_bytes
2424
from signedjson.sign import SignatureVerifyException, verify_signed_json
2525
from unpaddedbase64 import decode_base64
@@ -35,7 +35,7 @@
3535
get_domain_from_id,
3636
get_verify_key_from_cross_signing_key,
3737
)
38-
from synapse.util import unwrapFirstError
38+
from synapse.util import json_decoder, unwrapFirstError
3939
from synapse.util.async_helpers import Linearizer
4040
from synapse.util.caches.expiringcache import ExpiringCache
4141
from synapse.util.retryutils import NotRetryingDestination
@@ -404,7 +404,7 @@ async def claim_one_time_keys(self, query, timeout):
404404
for device_id, keys in device_keys.items():
405405
for key_id, json_bytes in keys.items():
406406
json_result.setdefault(user_id, {})[device_id] = {
407-
key_id: json.loads(json_bytes)
407+
key_id: json_decoder.decode(json_bytes)
408408
}
409409

410410
@trace
@@ -1186,7 +1186,7 @@ def _exception_to_failure(e):
11861186

11871187

11881188
def _one_time_keys_match(old_key_json, new_key):
1189-
old_key = json.loads(old_key_json)
1189+
old_key = json_decoder.decode(old_key_json)
11901190

11911191
# if either is a string rather than an object, they must match exactly
11921192
if not isinstance(old_key, dict) or not isinstance(new_key, dict):

synapse/handlers/federation.py

+5-11
Original file line numberDiff line numberDiff line change
@@ -1787,9 +1787,7 @@ async def get_state_for_pdu(self, room_id: str, event_id: str) -> List[EventBase
17871787
"""Returns the state at the event. i.e. not including said event.
17881788
"""
17891789

1790-
event = await self.store.get_event(
1791-
event_id, allow_none=False, check_room_id=room_id
1792-
)
1790+
event = await self.store.get_event(event_id, check_room_id=room_id)
17931791

17941792
state_groups = await self.state_store.get_state_groups(room_id, [event_id])
17951793

@@ -1815,9 +1813,7 @@ async def get_state_for_pdu(self, room_id: str, event_id: str) -> List[EventBase
18151813
async def get_state_ids_for_pdu(self, room_id: str, event_id: str) -> List[str]:
18161814
"""Returns the state at the event. i.e. not including said event.
18171815
"""
1818-
event = await self.store.get_event(
1819-
event_id, allow_none=False, check_room_id=room_id
1820-
)
1816+
event = await self.store.get_event(event_id, check_room_id=room_id)
18211817

18221818
state_groups = await self.state_store.get_state_groups_ids(room_id, [event_id])
18231819

@@ -2165,9 +2161,9 @@ async def _check_for_soft_fail(
21652161
auth_types = auth_types_for_event(event)
21662162
current_state_ids = [e for k, e in current_state_ids.items() if k in auth_types]
21672163

2168-
current_auth_events = await self.store.get_events(current_state_ids)
2164+
auth_events_map = await self.store.get_events(current_state_ids)
21692165
current_auth_events = {
2170-
(e.type, e.state_key): e for e in current_auth_events.values()
2166+
(e.type, e.state_key): e for e in auth_events_map.values()
21712167
}
21722168

21732169
try:
@@ -2183,9 +2179,7 @@ async def on_query_auth(
21832179
if not in_room:
21842180
raise AuthError(403, "Host not in room.")
21852181

2186-
event = await self.store.get_event(
2187-
event_id, allow_none=False, check_room_id=room_id
2188-
)
2182+
event = await self.store.get_event(event_id, check_room_id=room_id)
21892183

21902184
# Just go through and process each event in `remote_auth_chain`. We
21912185
# don't want to fall into the trap of `missing` being wrong.

synapse/handlers/identity.py

+18-23
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,6 @@
2121
import urllib.parse
2222
from typing import Awaitable, Callable, Dict, List, Optional, Tuple
2323

24-
from canonicaljson import json
25-
26-
from twisted.internet import defer
2724
from twisted.internet.error import TimeoutError
2825

2926
from synapse.api.errors import (
@@ -37,6 +34,7 @@
3734
from synapse.config.emailconfig import ThreepidBehaviour
3835
from synapse.http.client import SimpleHttpClient
3936
from synapse.types import JsonDict, Requester
37+
from synapse.util import json_decoder
4038
from synapse.util.hash import sha256_and_url_safe_base64
4139
from synapse.util.stringutils import assert_valid_client_secret, random_string
4240

@@ -197,7 +195,7 @@ async def bind_threepid(
197195
except TimeoutError:
198196
raise SynapseError(500, "Timed out contacting identity server")
199197
except CodeMessageException as e:
200-
data = json.loads(e.msg) # XXX WAT?
198+
data = json_decoder.decode(e.msg) # XXX WAT?
201199
return data
202200

203201
logger.info("Got 404 when POSTing JSON %s, falling back to v1 URL", bind_url)
@@ -620,18 +618,19 @@ async def proxy_msisdn_submit_token(
620618
# the CS API. They should be consolidated with those in RoomMemberHandler
621619
# https://github.com/matrix-org/synapse-dinsic/issues/25
622620

623-
@defer.inlineCallbacks
624-
def proxy_lookup_3pid(self, id_server, medium, address):
621+
async def proxy_lookup_3pid(
622+
self, id_server: str, medium: str, address: str
623+
) -> JsonDict:
625624
"""Looks up a 3pid in the passed identity server.
626625
627626
Args:
628-
id_server (str): The server name (including port, if required)
627+
id_server: The server name (including port, if required)
629628
of the identity server to use.
630-
medium (str): The type of the third party identifier (e.g. "email").
631-
address (str): The third party identifier (e.g. "foo@example.com").
629+
medium: The type of the third party identifier (e.g. "email").
630+
address: The third party identifier (e.g. "foo@example.com").
632631
633632
Returns:
634-
Deferred[dict]: The result of the lookup. See
633+
The result of the lookup. See
635634
https://matrix.org/docs/spec/identity_service/r0.1.0.html#association-lookup
636635
for details
637636
"""
@@ -643,16 +642,11 @@ def proxy_lookup_3pid(self, id_server, medium, address):
643642
id_server_url = self.rewrite_id_server_url(id_server, add_https=True)
644643

645644
try:
646-
data = yield self.http_client.get_json(
645+
data = await self.http_client.get_json(
647646
"%s/_matrix/identity/api/v1/lookup" % (id_server_url,),
648647
{"medium": medium, "address": address},
649648
)
650649

651-
if "mxid" in data:
652-
if "signatures" not in data:
653-
raise AuthError(401, "No signatures on 3pid binding")
654-
yield self._verify_any_signature(data, id_server)
655-
656650
except HttpResponseException as e:
657651
logger.info("Proxied lookup failed: %r", e)
658652
raise e.to_synapse_error()
@@ -662,18 +656,19 @@ def proxy_lookup_3pid(self, id_server, medium, address):
662656

663657
return data
664658

665-
@defer.inlineCallbacks
666-
def proxy_bulk_lookup_3pid(self, id_server, threepids):
659+
async def proxy_bulk_lookup_3pid(
660+
self, id_server: str, threepids: List[List[str]]
661+
) -> JsonDict:
667662
"""Looks up given 3pids in the passed identity server.
668663
669664
Args:
670-
id_server (str): The server name (including port, if required)
665+
id_server: The server name (including port, if required)
671666
of the identity server to use.
672-
threepids ([[str, str]]): The third party identifiers to lookup, as
667+
threepids: The third party identifiers to lookup, as
673668
a list of 2-string sized lists ([medium, address]).
674669
675670
Returns:
676-
Deferred[dict]: The result of the lookup. See
671+
The result of the lookup. See
677672
https://matrix.org/docs/spec/identity_service/r0.1.0.html#association-lookup
678673
for details
679674
"""
@@ -685,7 +680,7 @@ def proxy_bulk_lookup_3pid(self, id_server, threepids):
685680
id_server_url = self.rewrite_id_server_url(id_server, add_https=True)
686681

687682
try:
688-
data = yield self.http_client.post_json_get_json(
683+
data = await self.http_client.post_json_get_json(
689684
"%s/_matrix/identity/api/v1/bulk_lookup" % (id_server_url,),
690685
{"threepids": threepids},
691686
)
@@ -697,7 +692,7 @@ def proxy_bulk_lookup_3pid(self, id_server, threepids):
697692
logger.info("Failed to contact %s: %s", id_server, e)
698693
raise ProxiedRequestError(503, "Failed to contact identity server")
699694

700-
defer.returnValue(data)
695+
return data
701696

702697
async def lookup_3pid(
703698
self,

synapse/handlers/message.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import logging
1818
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
1919

20-
from canonicaljson import encode_canonical_json, json
20+
from canonicaljson import encode_canonical_json
2121

2222
from twisted.internet.interfaces import IDelayedCall
2323

@@ -55,6 +55,7 @@
5555
UserID,
5656
create_requester,
5757
)
58+
from synapse.util import json_decoder
5859
from synapse.util.async_helpers import Linearizer
5960
from synapse.util.frozenutils import frozendict_json_encoder
6061
from synapse.util.metrics import measure_func
@@ -867,7 +868,7 @@ async def handle_new_client_event(
867868
# Ensure that we can round trip before trying to persist in db
868869
try:
869870
dump = frozendict_json_encoder.encode(event.content)
870-
json.loads(dump)
871+
json_decoder.decode(dump)
871872
except Exception:
872873
logger.exception("Failed to encode content: %r", event.content)
873874
raise
@@ -963,7 +964,7 @@ async def persist_and_notify_client_event(
963964
allow_none=True,
964965
)
965966

966-
is_admin_redaction = (
967+
is_admin_redaction = bool(
967968
original_event and event.sender != original_event.sender
968969
)
969970

@@ -1083,8 +1084,8 @@ def is_inviter_member_event(e):
10831084
auth_events_ids = self.auth.compute_auth_events(
10841085
event, prev_state_ids, for_verification=True
10851086
)
1086-
auth_events = await self.store.get_events(auth_events_ids)
1087-
auth_events = {(e.type, e.state_key): e for e in auth_events.values()}
1087+
auth_events_map = await self.store.get_events(auth_events_ids)
1088+
auth_events = {(e.type, e.state_key): e for e in auth_events_map.values()}
10881089

10891090
room_version = await self.store.get_room_version_id(event.room_id)
10901091
room_version_obj = KNOWN_ROOM_VERSIONS[room_version]

0 commit comments

Comments
 (0)