You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1978 lines
82 KiB

  1. # Copyright 2014-2022 The Matrix.org Foundation C.I.C.
  2. # Copyright 2020 Sorunome
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Contains handlers for federation events."""
  16. import enum
  17. import itertools
  18. import logging
  19. from enum import Enum
  20. from http import HTTPStatus
  21. from typing import (
  22. TYPE_CHECKING,
  23. Collection,
  24. Dict,
  25. Iterable,
  26. List,
  27. Optional,
  28. Set,
  29. Tuple,
  30. Union,
  31. )
  32. import attr
  33. from prometheus_client import Histogram
  34. from signedjson.key import decode_verify_key_bytes
  35. from signedjson.sign import verify_signed_json
  36. from unpaddedbase64 import decode_base64
  37. from synapse import event_auth
  38. from synapse.api.constants import MAX_DEPTH, EventContentFields, EventTypes, Membership
  39. from synapse.api.errors import (
  40. AuthError,
  41. CodeMessageException,
  42. Codes,
  43. FederationDeniedError,
  44. FederationError,
  45. FederationPullAttemptBackoffError,
  46. HttpResponseException,
  47. NotFoundError,
  48. RequestSendFailed,
  49. SynapseError,
  50. )
  51. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
  52. from synapse.crypto.event_signing import compute_event_signature
  53. from synapse.event_auth import validate_event_for_room_version
  54. from synapse.events import EventBase
  55. from synapse.events.snapshot import EventContext
  56. from synapse.events.validator import EventValidator
  57. from synapse.federation.federation_client import InvalidResponseError
  58. from synapse.http.servlet import assert_params_in_dict
  59. from synapse.logging.context import nested_logging_context
  60. from synapse.logging.opentracing import SynapseTags, set_tag, tag_args, trace
  61. from synapse.metrics.background_process_metrics import run_as_background_process
  62. from synapse.module_api import NOT_SPAM
  63. from synapse.replication.http.federation import (
  64. ReplicationCleanRoomRestServlet,
  65. ReplicationStoreRoomOnOutlierMembershipRestServlet,
  66. )
  67. from synapse.storage.databases.main.events import PartialStateConflictError
  68. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  69. from synapse.types import JsonDict, get_domain_from_id
  70. from synapse.types.state import StateFilter
  71. from synapse.util.async_helpers import Linearizer
  72. from synapse.util.retryutils import NotRetryingDestination
  73. from synapse.visibility import filter_events_for_server
  74. if TYPE_CHECKING:
  75. from synapse.server import HomeServer
  76. logger = logging.getLogger(__name__)
  77. # Added to debug performance and track progress on optimizations
  78. backfill_processing_before_timer = Histogram(
  79. "synapse_federation_backfill_processing_before_time_seconds",
  80. "sec",
  81. [],
  82. buckets=(
  83. 0.1,
  84. 0.5,
  85. 1.0,
  86. 2.5,
  87. 5.0,
  88. 7.5,
  89. 10.0,
  90. 15.0,
  91. 20.0,
  92. 30.0,
  93. 40.0,
  94. 60.0,
  95. 80.0,
  96. "+Inf",
  97. ),
  98. )
  99. class _BackfillPointType(Enum):
  100. # a regular backwards extremity (ie, an event which we don't yet have, but which
  101. # is referred to by other events in the DAG)
  102. BACKWARDS_EXTREMITY = enum.auto()
  103. # an MSC2716 "insertion event"
  104. INSERTION_PONT = enum.auto()
  105. @attr.s(slots=True, auto_attribs=True, frozen=True)
  106. class _BackfillPoint:
  107. """A potential point we might backfill from"""
  108. event_id: str
  109. depth: int
  110. type: _BackfillPointType
  111. class FederationHandler:
  112. """Handles general incoming federation requests
  113. Incoming events are *not* handled here, for which see FederationEventHandler.
  114. """
  115. def __init__(self, hs: "HomeServer"):
  116. self.hs = hs
  117. self.clock = hs.get_clock()
  118. self.store = hs.get_datastores().main
  119. self._storage_controllers = hs.get_storage_controllers()
  120. self._state_storage_controller = self._storage_controllers.state
  121. self.federation_client = hs.get_federation_client()
  122. self.state_handler = hs.get_state_handler()
  123. self.server_name = hs.hostname
  124. self.keyring = hs.get_keyring()
  125. self.is_mine_id = hs.is_mine_id
  126. self.spam_checker = hs.get_spam_checker()
  127. self.event_creation_handler = hs.get_event_creation_handler()
  128. self.event_builder_factory = hs.get_event_builder_factory()
  129. self._event_auth_handler = hs.get_event_auth_handler()
  130. self._server_notices_mxid = hs.config.servernotices.server_notices_mxid
  131. self.config = hs.config
  132. self.http_client = hs.get_proxied_blacklisted_http_client()
  133. self._replication = hs.get_replication_data_handler()
  134. self._federation_event_handler = hs.get_federation_event_handler()
  135. self._device_handler = hs.get_device_handler()
  136. self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()
  137. self._notifier = hs.get_notifier()
  138. self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(
  139. hs
  140. )
  141. if hs.config.worker.worker_app:
  142. self._maybe_store_room_on_outlier_membership = (
  143. ReplicationStoreRoomOnOutlierMembershipRestServlet.make_client(hs)
  144. )
  145. else:
  146. self._maybe_store_room_on_outlier_membership = (
  147. self.store.maybe_store_room_on_outlier_membership
  148. )
  149. self._room_backfill = Linearizer("room_backfill")
  150. self.third_party_event_rules = hs.get_third_party_event_rules()
  151. # Tracks running partial state syncs by room ID.
  152. # Partial state syncs currently only run on the main process, so it's okay to
  153. # track them in-memory for now.
  154. self._active_partial_state_syncs: Set[str] = set()
  155. # Tracks partial state syncs we may want to restart.
  156. # A dictionary mapping room IDs to (initial destination, other destinations)
  157. # tuples.
  158. self._partial_state_syncs_maybe_needing_restart: Dict[
  159. str, Tuple[Optional[str], Collection[str]]
  160. ] = {}
  161. # A lock guarding the partial state flag for rooms.
  162. # When the lock is held for a given room, no other concurrent code may
  163. # partial state or un-partial state the room.
  164. self._is_partial_state_room_linearizer = Linearizer(
  165. name="_is_partial_state_room_linearizer"
  166. )
  167. # if this is the main process, fire off a background process to resume
  168. # any partial-state-resync operations which were in flight when we
  169. # were shut down.
  170. if not hs.config.worker.worker_app:
  171. run_as_background_process(
  172. "resume_sync_partial_state_room", self._resume_partial_state_room_sync
  173. )
  174. @trace
  175. async def maybe_backfill(
  176. self, room_id: str, current_depth: int, limit: int
  177. ) -> bool:
  178. """Checks the database to see if we should backfill before paginating,
  179. and if so do.
  180. Args:
  181. room_id
  182. current_depth: The depth from which we're paginating from. This is
  183. used to decide if we should backfill and what extremities to
  184. use.
  185. limit: The number of events that the pagination request will
  186. return. This is used as part of the heuristic to decide if we
  187. should back paginate.
  188. """
  189. # Starting the processing time here so we can include the room backfill
  190. # linearizer lock queue in the timing
  191. processing_start_time = self.clock.time_msec()
  192. async with self._room_backfill.queue(room_id):
  193. return await self._maybe_backfill_inner(
  194. room_id,
  195. current_depth,
  196. limit,
  197. processing_start_time=processing_start_time,
  198. )
  199. async def _maybe_backfill_inner(
  200. self,
  201. room_id: str,
  202. current_depth: int,
  203. limit: int,
  204. *,
  205. processing_start_time: Optional[int],
  206. ) -> bool:
  207. """
  208. Checks whether the `current_depth` is at or approaching any backfill
  209. points in the room and if so, will backfill. We only care about
  210. checking backfill points that happened before the `current_depth`
  211. (meaning less than or equal to the `current_depth`).
  212. Args:
  213. room_id: The room to backfill in.
  214. current_depth: The depth to check at for any upcoming backfill points.
  215. limit: The max number of events to request from the remote federated server.
  216. processing_start_time: The time when `maybe_backfill` started processing.
  217. Only used for timing. If `None`, no timing observation will be made.
  218. """
  219. backwards_extremities = [
  220. _BackfillPoint(event_id, depth, _BackfillPointType.BACKWARDS_EXTREMITY)
  221. for event_id, depth in await self.store.get_backfill_points_in_room(
  222. room_id=room_id,
  223. current_depth=current_depth,
  224. # We only need to end up with 5 extremities combined with the
  225. # insertion event extremities to make the `/backfill` request
  226. # but fetch an order of magnitude more to make sure there is
  227. # enough even after we filter them by whether visible in the
  228. # history. This isn't fool-proof as all backfill points within
  229. # our limit could be filtered out but seems like a good amount
  230. # to try with at least.
  231. limit=50,
  232. )
  233. ]
  234. insertion_events_to_be_backfilled: List[_BackfillPoint] = []
  235. if self.hs.config.experimental.msc2716_enabled:
  236. insertion_events_to_be_backfilled = [
  237. _BackfillPoint(event_id, depth, _BackfillPointType.INSERTION_PONT)
  238. for event_id, depth in await self.store.get_insertion_event_backward_extremities_in_room(
  239. room_id=room_id,
  240. current_depth=current_depth,
  241. # We only need to end up with 5 extremities combined with
  242. # the backfill points to make the `/backfill` request ...
  243. # (see the other comment above for more context).
  244. limit=50,
  245. )
  246. ]
  247. logger.debug(
  248. "_maybe_backfill_inner: backwards_extremities=%s insertion_events_to_be_backfilled=%s",
  249. backwards_extremities,
  250. insertion_events_to_be_backfilled,
  251. )
  252. # we now have a list of potential places to backpaginate from. We prefer to
  253. # start with the most recent (ie, max depth), so let's sort the list.
  254. sorted_backfill_points: List[_BackfillPoint] = sorted(
  255. itertools.chain(
  256. backwards_extremities,
  257. insertion_events_to_be_backfilled,
  258. ),
  259. key=lambda e: -int(e.depth),
  260. )
  261. logger.debug(
  262. "_maybe_backfill_inner: room_id: %s: current_depth: %s, limit: %s, "
  263. "backfill points (%d): %s",
  264. room_id,
  265. current_depth,
  266. limit,
  267. len(sorted_backfill_points),
  268. sorted_backfill_points,
  269. )
  270. # If we have no backfill points lower than the `current_depth` then
  271. # either we can a) bail or b) still attempt to backfill. We opt to try
  272. # backfilling anyway just in case we do get relevant events.
  273. if not sorted_backfill_points and current_depth != MAX_DEPTH:
  274. logger.debug(
  275. "_maybe_backfill_inner: all backfill points are *after* current depth. Trying again with later backfill points."
  276. )
  277. return await self._maybe_backfill_inner(
  278. room_id=room_id,
  279. # We use `MAX_DEPTH` so that we find all backfill points next
  280. # time (all events are below the `MAX_DEPTH`)
  281. current_depth=MAX_DEPTH,
  282. limit=limit,
  283. # We don't want to start another timing observation from this
  284. # nested recursive call. The top-most call can record the time
  285. # overall otherwise the smaller one will throw off the results.
  286. processing_start_time=None,
  287. )
  288. # Even after recursing with `MAX_DEPTH`, we didn't find any
  289. # backward extremities to backfill from.
  290. if not sorted_backfill_points:
  291. logger.debug(
  292. "_maybe_backfill_inner: Not backfilling as no backward extremeties found."
  293. )
  294. return False
  295. # If we're approaching an extremity we trigger a backfill, otherwise we
  296. # no-op.
  297. #
  298. # We chose twice the limit here as then clients paginating backwards
  299. # will send pagination requests that trigger backfill at least twice
  300. # using the most recent extremity before it gets removed (see below). We
  301. # chose more than one times the limit in case of failure, but choosing a
  302. # much larger factor will result in triggering a backfill request much
  303. # earlier than necessary.
  304. max_depth_of_backfill_points = sorted_backfill_points[0].depth
  305. if current_depth - 2 * limit > max_depth_of_backfill_points:
  306. logger.debug(
  307. "Not backfilling as we don't need to. %d < %d - 2 * %d",
  308. max_depth_of_backfill_points,
  309. current_depth,
  310. limit,
  311. )
  312. return False
  313. # For performance's sake, we only want to paginate from a particular extremity
  314. # if we can actually see the events we'll get. Otherwise, we'd just spend a lot
  315. # of resources to get redacted events. We check each extremity in turn and
  316. # ignore those which users on our server wouldn't be able to see.
  317. #
  318. # Additionally, we limit ourselves to backfilling from at most 5 extremities,
  319. # for two reasons:
  320. #
  321. # - The check which determines if we can see an extremity's events can be
  322. # expensive (we load the full state for the room at each of the backfill
  323. # points, or (worse) their successors)
  324. # - We want to avoid the server-server API request URI becoming too long.
  325. #
  326. # *Note*: the spec wants us to keep backfilling until we reach the start
  327. # of the room in case we are allowed to see some of the history. However,
  328. # in practice that causes more issues than its worth, as (a) it's
  329. # relatively rare for there to be any visible history and (b) even when
  330. # there is it's often sufficiently long ago that clients would stop
  331. # attempting to paginate before backfill reached the visible history.
  332. extremities_to_request: List[str] = []
  333. for bp in sorted_backfill_points:
  334. if len(extremities_to_request) >= 5:
  335. break
  336. # For regular backwards extremities, we don't have the extremity events
  337. # themselves, so we need to actually check the events that reference them -
  338. # their "successor" events.
  339. #
  340. # TODO: Correctly handle the case where we are allowed to see the
  341. # successor event but not the backward extremity, e.g. in the case of
  342. # initial join of the server where we are allowed to see the join
  343. # event but not anything before it. This would require looking at the
  344. # state *before* the event, ignoring the special casing certain event
  345. # types have.
  346. if bp.type == _BackfillPointType.INSERTION_PONT:
  347. event_ids_to_check = [bp.event_id]
  348. else:
  349. event_ids_to_check = await self.store.get_successor_events(bp.event_id)
  350. events_to_check = await self.store.get_events_as_list(
  351. event_ids_to_check,
  352. redact_behaviour=EventRedactBehaviour.as_is,
  353. get_prev_content=False,
  354. )
  355. # We set `check_history_visibility_only` as we might otherwise get false
  356. # positives from users having been erased.
  357. filtered_extremities = await filter_events_for_server(
  358. self._storage_controllers,
  359. self.server_name,
  360. self.server_name,
  361. events_to_check,
  362. redact=False,
  363. check_history_visibility_only=True,
  364. )
  365. if filtered_extremities:
  366. extremities_to_request.append(bp.event_id)
  367. else:
  368. logger.debug(
  369. "_maybe_backfill_inner: skipping extremity %s as it would not be visible",
  370. bp,
  371. )
  372. if not extremities_to_request:
  373. logger.debug(
  374. "_maybe_backfill_inner: found no extremities which would be visible"
  375. )
  376. return False
  377. logger.debug(
  378. "_maybe_backfill_inner: extremities_to_request %s", extremities_to_request
  379. )
  380. set_tag(
  381. SynapseTags.RESULT_PREFIX + "extremities_to_request",
  382. str(extremities_to_request),
  383. )
  384. set_tag(
  385. SynapseTags.RESULT_PREFIX + "extremities_to_request.length",
  386. str(len(extremities_to_request)),
  387. )
  388. # Now we need to decide which hosts to hit first.
  389. # First we try hosts that are already in the room.
  390. # TODO: HEURISTIC ALERT.
  391. likely_domains = (
  392. await self._storage_controllers.state.get_current_hosts_in_room_ordered(
  393. room_id
  394. )
  395. )
  396. async def try_backfill(domains: Collection[str]) -> bool:
  397. # TODO: Should we try multiple of these at a time?
  398. # Number of contacted remote homeservers that have denied our backfill
  399. # request with a 4xx code.
  400. denied_count = 0
  401. # Maximum number of contacted remote homeservers that can deny our
  402. # backfill request with 4xx codes before we give up.
  403. max_denied_count = 5
  404. for dom in domains:
  405. # We don't want to ask our own server for information we don't have
  406. if dom == self.server_name:
  407. continue
  408. try:
  409. await self._federation_event_handler.backfill(
  410. dom, room_id, limit=100, extremities=extremities_to_request
  411. )
  412. # If this succeeded then we probably already have the
  413. # appropriate stuff.
  414. # TODO: We can probably do something more intelligent here.
  415. return True
  416. except NotRetryingDestination as e:
  417. logger.info("_maybe_backfill_inner: %s", e)
  418. continue
  419. except FederationDeniedError:
  420. logger.info(
  421. "_maybe_backfill_inner: Not attempting to backfill from %s because the homeserver is not on our federation whitelist",
  422. dom,
  423. )
  424. continue
  425. except (SynapseError, InvalidResponseError) as e:
  426. logger.info("Failed to backfill from %s because %s", dom, e)
  427. continue
  428. except HttpResponseException as e:
  429. if 400 <= e.code < 500:
  430. logger.warning(
  431. "Backfill denied from %s because %s [%d/%d]",
  432. dom,
  433. e,
  434. denied_count,
  435. max_denied_count,
  436. )
  437. denied_count += 1
  438. if denied_count >= max_denied_count:
  439. return False
  440. continue
  441. logger.info("Failed to backfill from %s because %s", dom, e)
  442. continue
  443. except CodeMessageException as e:
  444. if 400 <= e.code < 500:
  445. logger.warning(
  446. "Backfill denied from %s because %s [%d/%d]",
  447. dom,
  448. e,
  449. denied_count,
  450. max_denied_count,
  451. )
  452. denied_count += 1
  453. if denied_count >= max_denied_count:
  454. return False
  455. continue
  456. logger.info("Failed to backfill from %s because %s", dom, e)
  457. continue
  458. except RequestSendFailed as e:
  459. logger.info("Failed to get backfill from %s because %s", dom, e)
  460. continue
  461. except Exception as e:
  462. logger.exception("Failed to backfill from %s because %s", dom, e)
  463. continue
  464. return False
  465. # If we have the `processing_start_time`, then we can make an
  466. # observation. We wouldn't have the `processing_start_time` in the case
  467. # where `_maybe_backfill_inner` is recursively called to find any
  468. # backfill points regardless of `current_depth`.
  469. if processing_start_time is not None:
  470. processing_end_time = self.clock.time_msec()
  471. backfill_processing_before_timer.observe(
  472. (processing_end_time - processing_start_time) / 1000
  473. )
  474. success = await try_backfill(likely_domains)
  475. if success:
  476. return True
  477. # TODO: we could also try servers which were previously in the room, but
  478. # are no longer.
  479. return False
  480. async def send_invite(self, target_host: str, event: EventBase) -> EventBase:
  481. """Sends the invite to the remote server for signing.
  482. Invites must be signed by the invitee's server before distribution.
  483. """
  484. try:
  485. pdu = await self.federation_client.send_invite(
  486. destination=target_host,
  487. room_id=event.room_id,
  488. event_id=event.event_id,
  489. pdu=event,
  490. )
  491. except RequestSendFailed:
  492. raise SynapseError(502, f"Can't connect to server {target_host}")
  493. return pdu
  494. async def on_event_auth(self, event_id: str) -> List[EventBase]:
  495. event = await self.store.get_event(event_id)
  496. auth = await self.store.get_auth_chain(
  497. event.room_id, list(event.auth_event_ids()), include_given=True
  498. )
  499. return list(auth)
  500. async def do_invite_join(
  501. self, target_hosts: Iterable[str], room_id: str, joinee: str, content: JsonDict
  502. ) -> Tuple[str, int]:
  503. """Attempts to join the `joinee` to the room `room_id` via the
  504. servers contained in `target_hosts`.
  505. This first triggers a /make_join/ request that returns a partial
  506. event that we can fill out and sign. This is then sent to the
  507. remote server via /send_join/ which responds with the state at that
  508. event and the auth_chains.
  509. We suspend processing of any received events from this room until we
  510. have finished processing the join.
  511. Args:
  512. target_hosts: List of servers to attempt to join the room with.
  513. room_id: The ID of the room to join.
  514. joinee: The User ID of the joining user.
  515. content: The event content to use for the join event.
  516. """
  517. # TODO: We should be able to call this on workers, but the upgrading of
  518. # room stuff after join currently doesn't work on workers.
  519. # TODO: Before we relax this condition, we need to allow re-syncing of
  520. # partial room state to happen on workers.
  521. assert self.config.worker.worker_app is None
  522. logger.debug("Joining %s to %s", joinee, room_id)
  523. origin, event, room_version_obj = await self._make_and_verify_event(
  524. target_hosts,
  525. room_id,
  526. joinee,
  527. "join",
  528. content,
  529. params={"ver": KNOWN_ROOM_VERSIONS},
  530. )
  531. # This shouldn't happen, because the RoomMemberHandler has a
  532. # linearizer lock which only allows one operation per user per room
  533. # at a time - so this is just paranoia.
  534. assert room_id not in self._federation_event_handler.room_queues
  535. self._federation_event_handler.room_queues[room_id] = []
  536. is_host_joined = await self.store.is_host_joined(room_id, self.server_name)
  537. if not is_host_joined:
  538. # We may have old forward extremities lying around if the homeserver left
  539. # the room completely in the past. Clear them out.
  540. #
  541. # Note that this check-then-clear is subject to races where
  542. # * the homeserver is in the room and stops being in the room just after
  543. # the check. We won't reset the forward extremities, but that's okay,
  544. # since they will be almost up to date.
  545. # * the homeserver is not in the room and starts being in the room just
  546. # after the check. This can't happen, since `RoomMemberHandler` has a
  547. # linearizer lock which prevents concurrent remote joins into the same
  548. # room.
  549. # In short, the races either have an acceptable outcome or should be
  550. # impossible.
  551. await self._clean_room_for_join(room_id)
  552. try:
  553. # Try the host we successfully got a response to /make_join/
  554. # request first.
  555. host_list = list(target_hosts)
  556. try:
  557. host_list.remove(origin)
  558. host_list.insert(0, origin)
  559. except ValueError:
  560. pass
  561. async with self._is_partial_state_room_linearizer.queue(room_id):
  562. already_partial_state_room = await self.store.is_partial_state_room(
  563. room_id
  564. )
  565. ret = await self.federation_client.send_join(
  566. host_list,
  567. event,
  568. room_version_obj,
  569. # Perform a full join when we are already in the room and it is a
  570. # full state room, since we are not allowed to persist a partial
  571. # state join event in a full state room. In the future, we could
  572. # optimize this by always performing a partial state join and
  573. # computing the state ourselves or retrieving it from the remote
  574. # homeserver if necessary.
  575. #
  576. # There's a race where we leave the room, then perform a full join
  577. # anyway. This should end up being fast anyway, since we would
  578. # already have the full room state and auth chain persisted.
  579. partial_state=not is_host_joined or already_partial_state_room,
  580. )
  581. event = ret.event
  582. origin = ret.origin
  583. state = ret.state
  584. auth_chain = ret.auth_chain
  585. auth_chain.sort(key=lambda e: e.depth)
  586. logger.debug("do_invite_join auth_chain: %s", auth_chain)
  587. logger.debug("do_invite_join state: %s", state)
  588. logger.debug("do_invite_join event: %s", event)
  589. # if this is the first time we've joined this room, it's time to add
  590. # a row to `rooms` with the correct room version. If there's already a
  591. # row there, we should override it, since it may have been populated
  592. # based on an invite request which lied about the room version.
  593. #
  594. # federation_client.send_join has already checked that the room
  595. # version in the received create event is the same as room_version_obj,
  596. # so we can rely on it now.
  597. #
  598. await self.store.upsert_room_on_join(
  599. room_id=room_id,
  600. room_version=room_version_obj,
  601. state_events=state,
  602. )
  603. if ret.partial_state and not already_partial_state_room:
  604. # Mark the room as having partial state.
  605. # The background process is responsible for unmarking this flag,
  606. # even if the join fails.
  607. # TODO(faster_joins):
  608. # We may want to reset the partial state info if it's from an
  609. # old, failed partial state join.
  610. # https://github.com/matrix-org/synapse/issues/13000
  611. await self.store.store_partial_state_room(
  612. room_id=room_id,
  613. servers=ret.servers_in_room,
  614. device_lists_stream_id=self.store.get_device_stream_token(),
  615. joined_via=origin,
  616. )
  617. try:
  618. max_stream_id = (
  619. await self._federation_event_handler.process_remote_join(
  620. origin,
  621. room_id,
  622. auth_chain,
  623. state,
  624. event,
  625. room_version_obj,
  626. partial_state=ret.partial_state,
  627. )
  628. )
  629. except PartialStateConflictError:
  630. # This should be impossible, since we hold the lock on the room's
  631. # partial statedness.
  632. logger.error(
  633. "Room %s was un-partial stated while processing remote join.",
  634. room_id,
  635. )
  636. raise
  637. else:
  638. # Record the join event id for future use (when we finish the full
  639. # join). We have to do this after persisting the event to keep
  640. # foreign key constraints intact.
  641. if ret.partial_state and not already_partial_state_room:
  642. # TODO(faster_joins):
  643. # We may want to reset the partial state info if it's from
  644. # an old, failed partial state join.
  645. # https://github.com/matrix-org/synapse/issues/13000
  646. await self.store.write_partial_state_rooms_join_event_id(
  647. room_id, event.event_id
  648. )
  649. finally:
  650. # Always kick off the background process that asynchronously fetches
  651. # state for the room.
  652. # If the join failed, the background process is responsible for
  653. # cleaning up — including unmarking the room as a partial state
  654. # room.
  655. if ret.partial_state:
  656. # Kick off the process of asynchronously fetching the state for
  657. # this room.
  658. self._start_partial_state_room_sync(
  659. initial_destination=origin,
  660. other_destinations=ret.servers_in_room,
  661. room_id=room_id,
  662. )
  663. # We wait here until this instance has seen the events come down
  664. # replication (if we're using replication) as the below uses caches.
  665. await self._replication.wait_for_stream_position(
  666. self.config.worker.events_shard_config.get_instance(room_id),
  667. "events",
  668. max_stream_id,
  669. )
  670. # Check whether this room is the result of an upgrade of a room we already know
  671. # about. If so, migrate over user information
  672. predecessor = await self.store.get_room_predecessor(room_id)
  673. if not predecessor or not isinstance(predecessor.get("room_id"), str):
  674. return event.event_id, max_stream_id
  675. old_room_id = predecessor["room_id"]
  676. logger.debug(
  677. "Found predecessor for %s during remote join: %s", room_id, old_room_id
  678. )
  679. # We retrieve the room member handler here as to not cause a cyclic dependency
  680. member_handler = self.hs.get_room_member_handler()
  681. await member_handler.transfer_room_state_on_room_upgrade(
  682. old_room_id, room_id
  683. )
  684. logger.debug("Finished joining %s to %s", joinee, room_id)
  685. return event.event_id, max_stream_id
  686. finally:
  687. room_queue = self._federation_event_handler.room_queues[room_id]
  688. del self._federation_event_handler.room_queues[room_id]
  689. # we don't need to wait for the queued events to be processed -
  690. # it's just a best-effort thing at this point. We do want to do
  691. # them roughly in order, though, otherwise we'll end up making
  692. # lots of requests for missing prev_events which we do actually
  693. # have. Hence we fire off the background task, but don't wait for it.
  694. run_as_background_process(
  695. "handle_queued_pdus", self._handle_queued_pdus, room_queue
  696. )
  697. async def do_knock(
  698. self,
  699. target_hosts: List[str],
  700. room_id: str,
  701. knockee: str,
  702. content: JsonDict,
  703. ) -> Tuple[str, int]:
  704. """Sends the knock to the remote server.
  705. This first triggers a make_knock request that returns a partial
  706. event that we can fill out and sign. This is then sent to the
  707. remote server via send_knock.
  708. Knock events must be signed by the knockee's server before distributing.
  709. Args:
  710. target_hosts: A list of hosts that we want to try knocking through.
  711. room_id: The ID of the room to knock on.
  712. knockee: The ID of the user who is knocking.
  713. content: The content of the knock event.
  714. Returns:
  715. A tuple of (event ID, stream ID).
  716. Raises:
  717. SynapseError: If the chosen remote server returns a 3xx/4xx code.
  718. RuntimeError: If no servers were reachable.
  719. """
  720. logger.debug("Knocking on room %s on behalf of user %s", room_id, knockee)
  721. # Inform the remote server of the room versions we support
  722. supported_room_versions = list(KNOWN_ROOM_VERSIONS.keys())
  723. # Ask the remote server to create a valid knock event for us. Once received,
  724. # we sign the event
  725. params: Dict[str, Iterable[str]] = {"ver": supported_room_versions}
  726. origin, event, event_format_version = await self._make_and_verify_event(
  727. target_hosts, room_id, knockee, Membership.KNOCK, content, params=params
  728. )
  729. # Mark the knock as an outlier as we don't yet have the state at this point in
  730. # the DAG.
  731. event.internal_metadata.outlier = True
  732. # ... but tell /sync to send it to clients anyway.
  733. event.internal_metadata.out_of_band_membership = True
  734. # Record the room ID and its version so that we have a record of the room
  735. await self._maybe_store_room_on_outlier_membership(
  736. room_id=event.room_id, room_version=event_format_version
  737. )
  738. # Initially try the host that we successfully called /make_knock on
  739. try:
  740. target_hosts.remove(origin)
  741. target_hosts.insert(0, origin)
  742. except ValueError:
  743. pass
  744. # Send the signed event back to the room, and potentially receive some
  745. # further information about the room in the form of partial state events
  746. knock_response = await self.federation_client.send_knock(target_hosts, event)
  747. # Store any stripped room state events in the "unsigned" key of the event.
  748. # This is a bit of a hack and is cribbing off of invites. Basically we
  749. # store the room state here and retrieve it again when this event appears
  750. # in the invitee's sync stream. It is stripped out for all other local users.
  751. stripped_room_state = (
  752. knock_response.get("knock_room_state")
  753. # Since v1.37, Synapse incorrectly used "knock_state_events" for this field.
  754. # Thus, we also check for a 'knock_state_events' to support old instances.
  755. # See https://github.com/matrix-org/synapse/issues/14088.
  756. or knock_response.get("knock_state_events")
  757. )
  758. if stripped_room_state is None:
  759. raise KeyError(
  760. "Missing 'knock_room_state' (or legacy 'knock_state_events') field in "
  761. "send_knock response"
  762. )
  763. event.unsigned["knock_room_state"] = stripped_room_state
  764. context = EventContext.for_outlier(self._storage_controllers)
  765. stream_id = await self._federation_event_handler.persist_events_and_notify(
  766. event.room_id, [(event, context)]
  767. )
  768. return event.event_id, stream_id
  769. async def _handle_queued_pdus(
  770. self, room_queue: List[Tuple[EventBase, str]]
  771. ) -> None:
  772. """Process PDUs which got queued up while we were busy send_joining.
  773. Args:
  774. room_queue: list of PDUs to be processed and the servers that sent them
  775. """
  776. for p, origin in room_queue:
  777. try:
  778. logger.info(
  779. "Processing queued PDU %s which was received while we were joining",
  780. p,
  781. )
  782. with nested_logging_context(p.event_id):
  783. await self._federation_event_handler.on_receive_pdu(origin, p)
  784. except Exception as e:
  785. logger.warning(
  786. "Error handling queued PDU %s from %s: %s", p.event_id, origin, e
  787. )
  788. async def on_make_join_request(
  789. self, origin: str, room_id: str, user_id: str
  790. ) -> EventBase:
  791. """We've received a /make_join/ request, so we create a partial
  792. join event for the room and return that. We do *not* persist or
  793. process it until the other server has signed it and sent it back.
  794. Args:
  795. origin: The (verified) server name of the requesting server.
  796. room_id: Room to create join event in
  797. user_id: The user to create the join for
  798. """
  799. if get_domain_from_id(user_id) != origin:
  800. logger.info(
  801. "Got /make_join request for user %r from different origin %s, ignoring",
  802. user_id,
  803. origin,
  804. )
  805. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  806. # checking the room version will check that we've actually heard of the room
  807. # (and return a 404 otherwise)
  808. room_version = await self.store.get_room_version(room_id)
  809. if await self.store.is_partial_state_room(room_id):
  810. # If our server is still only partially joined, we can't give a complete
  811. # response to /make_join, so return a 404 as we would if we weren't in the
  812. # room at all.
  813. # The main reason we can't respond properly is that we need to know about
  814. # the auth events for the join event that we would return.
  815. # We also should not bother entertaining the /make_join since we cannot
  816. # handle the /send_join.
  817. logger.info(
  818. "Rejecting /make_join to %s because it's a partial state room", room_id
  819. )
  820. raise SynapseError(
  821. 404,
  822. "Unable to handle /make_join right now; this server is not fully joined.",
  823. errcode=Codes.NOT_FOUND,
  824. )
  825. # now check that we are *still* in the room
  826. is_in_room = await self._event_auth_handler.is_host_in_room(
  827. room_id, self.server_name
  828. )
  829. if not is_in_room:
  830. logger.info(
  831. "Got /make_join request for room %s we are no longer in",
  832. room_id,
  833. )
  834. raise NotFoundError("Not an active room on this server")
  835. event_content = {"membership": Membership.JOIN}
  836. # If the current room is using restricted join rules, additional information
  837. # may need to be included in the event content in order to efficiently
  838. # validate the event.
  839. #
  840. # Note that this requires the /send_join request to come back to the
  841. # same server.
  842. if room_version.msc3083_join_rules:
  843. state_ids = await self._state_storage_controller.get_current_state_ids(
  844. room_id
  845. )
  846. if await self._event_auth_handler.has_restricted_join_rules(
  847. state_ids, room_version
  848. ):
  849. prev_member_event_id = state_ids.get((EventTypes.Member, user_id), None)
  850. # If the user is invited or joined to the room already, then
  851. # no additional info is needed.
  852. include_auth_user_id = True
  853. if prev_member_event_id:
  854. prev_member_event = await self.store.get_event(prev_member_event_id)
  855. include_auth_user_id = prev_member_event.membership not in (
  856. Membership.JOIN,
  857. Membership.INVITE,
  858. )
  859. if include_auth_user_id:
  860. event_content[
  861. EventContentFields.AUTHORISING_USER
  862. ] = await self._event_auth_handler.get_user_which_could_invite(
  863. room_id,
  864. state_ids,
  865. )
  866. builder = self.event_builder_factory.for_room_version(
  867. room_version,
  868. {
  869. "type": EventTypes.Member,
  870. "content": event_content,
  871. "room_id": room_id,
  872. "sender": user_id,
  873. "state_key": user_id,
  874. },
  875. )
  876. try:
  877. event, context = await self.event_creation_handler.create_new_client_event(
  878. builder=builder
  879. )
  880. except SynapseError as e:
  881. logger.warning("Failed to create join to %s because %s", room_id, e)
  882. raise
  883. # Ensure the user can even join the room.
  884. await self._federation_event_handler.check_join_restrictions(context, event)
  885. # The remote hasn't signed it yet, obviously. We'll do the full checks
  886. # when we get the event back in `on_send_join_request`
  887. await self._event_auth_handler.check_auth_rules_from_context(event)
  888. return event
  889. async def on_invite_request(
  890. self, origin: str, event: EventBase, room_version: RoomVersion
  891. ) -> EventBase:
  892. """We've got an invite event. Process and persist it. Sign it.
  893. Respond with the now signed event.
  894. """
  895. if event.state_key is None:
  896. raise SynapseError(400, "The invite event did not have a state key")
  897. is_blocked = await self.store.is_room_blocked(event.room_id)
  898. if is_blocked:
  899. raise SynapseError(403, "This room has been blocked on this server")
  900. if self.hs.config.server.block_non_admin_invites:
  901. raise SynapseError(403, "This server does not accept room invites")
  902. spam_check = await self.spam_checker.user_may_invite(
  903. event.sender, event.state_key, event.room_id
  904. )
  905. if spam_check != NOT_SPAM:
  906. raise SynapseError(
  907. 403,
  908. "This user is not permitted to send invites to this server/user",
  909. errcode=spam_check[0],
  910. additional_fields=spam_check[1],
  911. )
  912. membership = event.content.get("membership")
  913. if event.type != EventTypes.Member or membership != Membership.INVITE:
  914. raise SynapseError(400, "The event was not an m.room.member invite event")
  915. sender_domain = get_domain_from_id(event.sender)
  916. if sender_domain != origin:
  917. raise SynapseError(
  918. 400, "The invite event was not from the server sending it"
  919. )
  920. if not self.is_mine_id(event.state_key):
  921. raise SynapseError(400, "The invite event must be for this server")
  922. # block any attempts to invite the server notices mxid
  923. if event.state_key == self._server_notices_mxid:
  924. raise SynapseError(HTTPStatus.FORBIDDEN, "Cannot invite this user")
  925. # We retrieve the room member handler here as to not cause a cyclic dependency
  926. member_handler = self.hs.get_room_member_handler()
  927. # We don't rate limit based on room ID, as that should be done by
  928. # sending server.
  929. await member_handler.ratelimit_invite(None, None, event.state_key)
  930. # keep a record of the room version, if we don't yet know it.
  931. # (this may get overwritten if we later get a different room version in a
  932. # join dance).
  933. await self._maybe_store_room_on_outlier_membership(
  934. room_id=event.room_id, room_version=room_version
  935. )
  936. event.internal_metadata.outlier = True
  937. event.internal_metadata.out_of_band_membership = True
  938. event.signatures.update(
  939. compute_event_signature(
  940. room_version,
  941. event.get_pdu_json(),
  942. self.hs.hostname,
  943. self.hs.signing_key,
  944. )
  945. )
  946. context = EventContext.for_outlier(self._storage_controllers)
  947. await self._bulk_push_rule_evaluator.action_for_events_by_user(
  948. [(event, context)]
  949. )
  950. try:
  951. await self._federation_event_handler.persist_events_and_notify(
  952. event.room_id, [(event, context)]
  953. )
  954. except Exception:
  955. await self.store.remove_push_actions_from_staging(event.event_id)
  956. raise
  957. return event
  958. async def do_remotely_reject_invite(
  959. self, target_hosts: Iterable[str], room_id: str, user_id: str, content: JsonDict
  960. ) -> Tuple[EventBase, int]:
  961. origin, event, room_version = await self._make_and_verify_event(
  962. target_hosts, room_id, user_id, "leave", content=content
  963. )
  964. # Mark as outlier as we don't have any state for this event; we're not
  965. # even in the room.
  966. event.internal_metadata.outlier = True
  967. event.internal_metadata.out_of_band_membership = True
  968. # Try the host that we successfully called /make_leave/ on first for
  969. # the /send_leave/ request.
  970. host_list = list(target_hosts)
  971. try:
  972. host_list.remove(origin)
  973. host_list.insert(0, origin)
  974. except ValueError:
  975. pass
  976. await self.federation_client.send_leave(host_list, event)
  977. context = EventContext.for_outlier(self._storage_controllers)
  978. stream_id = await self._federation_event_handler.persist_events_and_notify(
  979. event.room_id, [(event, context)]
  980. )
  981. return event, stream_id
  982. async def _make_and_verify_event(
  983. self,
  984. target_hosts: Iterable[str],
  985. room_id: str,
  986. user_id: str,
  987. membership: str,
  988. content: JsonDict,
  989. params: Optional[Dict[str, Union[str, Iterable[str]]]] = None,
  990. ) -> Tuple[str, EventBase, RoomVersion]:
  991. (
  992. origin,
  993. event,
  994. room_version,
  995. ) = await self.federation_client.make_membership_event(
  996. target_hosts, room_id, user_id, membership, content, params=params
  997. )
  998. logger.debug("Got response to make_%s: %s", membership, event)
  999. # We should assert some things.
  1000. # FIXME: Do this in a nicer way
  1001. assert event.type == EventTypes.Member
  1002. assert event.user_id == user_id
  1003. assert event.state_key == user_id
  1004. assert event.room_id == room_id
  1005. return origin, event, room_version
  1006. async def on_make_leave_request(
  1007. self, origin: str, room_id: str, user_id: str
  1008. ) -> EventBase:
  1009. """We've received a /make_leave/ request, so we create a partial
  1010. leave event for the room and return that. We do *not* persist or
  1011. process it until the other server has signed it and sent it back.
  1012. Args:
  1013. origin: The (verified) server name of the requesting server.
  1014. room_id: Room to create leave event in
  1015. user_id: The user to create the leave for
  1016. """
  1017. if get_domain_from_id(user_id) != origin:
  1018. logger.info(
  1019. "Got /make_leave request for user %r from different origin %s, ignoring",
  1020. user_id,
  1021. origin,
  1022. )
  1023. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  1024. room_version_obj = await self.store.get_room_version(room_id)
  1025. builder = self.event_builder_factory.for_room_version(
  1026. room_version_obj,
  1027. {
  1028. "type": EventTypes.Member,
  1029. "content": {"membership": Membership.LEAVE},
  1030. "room_id": room_id,
  1031. "sender": user_id,
  1032. "state_key": user_id,
  1033. },
  1034. )
  1035. event, context = await self.event_creation_handler.create_new_client_event(
  1036. builder=builder
  1037. )
  1038. try:
  1039. # The remote hasn't signed it yet, obviously. We'll do the full checks
  1040. # when we get the event back in `on_send_leave_request`
  1041. await self._event_auth_handler.check_auth_rules_from_context(event)
  1042. except AuthError as e:
  1043. logger.warning("Failed to create new leave %r because %s", event, e)
  1044. raise e
  1045. return event
  1046. async def on_make_knock_request(
  1047. self, origin: str, room_id: str, user_id: str
  1048. ) -> EventBase:
  1049. """We've received a make_knock request, so we create a partial
  1050. knock event for the room and return that. We do *not* persist or
  1051. process it until the other server has signed it and sent it back.
  1052. Args:
  1053. origin: The (verified) server name of the requesting server.
  1054. room_id: The room to create the knock event in.
  1055. user_id: The user to create the knock for.
  1056. Returns:
  1057. The partial knock event.
  1058. """
  1059. if get_domain_from_id(user_id) != origin:
  1060. logger.info(
  1061. "Get /make_knock request for user %r from different origin %s, ignoring",
  1062. user_id,
  1063. origin,
  1064. )
  1065. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  1066. room_version_obj = await self.store.get_room_version(room_id)
  1067. builder = self.event_builder_factory.for_room_version(
  1068. room_version_obj,
  1069. {
  1070. "type": EventTypes.Member,
  1071. "content": {"membership": Membership.KNOCK},
  1072. "room_id": room_id,
  1073. "sender": user_id,
  1074. "state_key": user_id,
  1075. },
  1076. )
  1077. event, context = await self.event_creation_handler.create_new_client_event(
  1078. builder=builder
  1079. )
  1080. event_allowed, _ = await self.third_party_event_rules.check_event_allowed(
  1081. event, context
  1082. )
  1083. if not event_allowed:
  1084. logger.warning("Creation of knock %s forbidden by third-party rules", event)
  1085. raise SynapseError(
  1086. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  1087. )
  1088. try:
  1089. # The remote hasn't signed it yet, obviously. We'll do the full checks
  1090. # when we get the event back in `on_send_knock_request`
  1091. await self._event_auth_handler.check_auth_rules_from_context(event)
  1092. except AuthError as e:
  1093. logger.warning("Failed to create new knock %r because %s", event, e)
  1094. raise e
  1095. return event
  1096. @trace
  1097. @tag_args
  1098. async def get_state_ids_for_pdu(self, room_id: str, event_id: str) -> List[str]:
  1099. """Returns the state at the event. i.e. not including said event."""
  1100. event = await self.store.get_event(event_id, check_room_id=room_id)
  1101. if event.internal_metadata.outlier:
  1102. raise NotFoundError("State not known at event %s" % (event_id,))
  1103. state_groups = await self._state_storage_controller.get_state_groups_ids(
  1104. room_id, [event_id]
  1105. )
  1106. # get_state_groups_ids should return exactly one result
  1107. assert len(state_groups) == 1
  1108. state_map = next(iter(state_groups.values()))
  1109. state_key = event.get_state_key()
  1110. if state_key is not None:
  1111. # the event was not rejected (get_event raises a NotFoundError for rejected
  1112. # events) so the state at the event should include the event itself.
  1113. assert (
  1114. state_map.get((event.type, state_key)) == event.event_id
  1115. ), "State at event did not include event itself"
  1116. # ... but we need the state *before* that event
  1117. if "replaces_state" in event.unsigned:
  1118. prev_id = event.unsigned["replaces_state"]
  1119. state_map[(event.type, state_key)] = prev_id
  1120. else:
  1121. del state_map[(event.type, state_key)]
  1122. return list(state_map.values())
  1123. async def on_backfill_request(
  1124. self, origin: str, room_id: str, pdu_list: List[str], limit: int
  1125. ) -> List[EventBase]:
  1126. # We allow partially joined rooms since in this case we are filtering out
  1127. # non-local events in `filter_events_for_server`.
  1128. await self._event_auth_handler.assert_host_in_room(room_id, origin, True)
  1129. # Synapse asks for 100 events per backfill request. Do not allow more.
  1130. limit = min(limit, 100)
  1131. events = await self.store.get_backfill_events(room_id, pdu_list, limit)
  1132. logger.debug(
  1133. "on_backfill_request: backfill events=%s",
  1134. [
  1135. "event_id=%s,depth=%d,body=%s,prevs=%s\n"
  1136. % (
  1137. event.event_id,
  1138. event.depth,
  1139. event.content.get("body", event.type),
  1140. event.prev_event_ids(),
  1141. )
  1142. for event in events
  1143. ],
  1144. )
  1145. events = await filter_events_for_server(
  1146. self._storage_controllers, origin, self.server_name, events
  1147. )
  1148. return events
  1149. async def get_persisted_pdu(
  1150. self, origin: str, event_id: str
  1151. ) -> Optional[EventBase]:
  1152. """Get an event from the database for the given server.
  1153. Args:
  1154. origin: hostname of server which is requesting the event; we
  1155. will check that the server is allowed to see it.
  1156. event_id: id of the event being requested
  1157. Returns:
  1158. None if we know nothing about the event; otherwise the (possibly-redacted) event.
  1159. Raises:
  1160. AuthError if the server is not currently in the room
  1161. """
  1162. event = await self.store.get_event(
  1163. event_id, allow_none=True, allow_rejected=True
  1164. )
  1165. if not event:
  1166. return None
  1167. await self._event_auth_handler.assert_host_in_room(event.room_id, origin)
  1168. events = await filter_events_for_server(
  1169. self._storage_controllers, origin, self.server_name, [event]
  1170. )
  1171. event = events[0]
  1172. return event
  1173. async def on_get_missing_events(
  1174. self,
  1175. origin: str,
  1176. room_id: str,
  1177. earliest_events: List[str],
  1178. latest_events: List[str],
  1179. limit: int,
  1180. ) -> List[EventBase]:
  1181. # We allow partially joined rooms since in this case we are filtering out
  1182. # non-local events in `filter_events_for_server`.
  1183. await self._event_auth_handler.assert_host_in_room(room_id, origin, True)
  1184. # Only allow up to 20 events to be retrieved per request.
  1185. limit = min(limit, 20)
  1186. missing_events = await self.store.get_missing_events(
  1187. room_id=room_id,
  1188. earliest_events=earliest_events,
  1189. latest_events=latest_events,
  1190. limit=limit,
  1191. )
  1192. missing_events = await filter_events_for_server(
  1193. self._storage_controllers, origin, self.server_name, missing_events
  1194. )
  1195. return missing_events
  1196. async def exchange_third_party_invite(
  1197. self, sender_user_id: str, target_user_id: str, room_id: str, signed: JsonDict
  1198. ) -> None:
  1199. third_party_invite = {"signed": signed}
  1200. event_dict = {
  1201. "type": EventTypes.Member,
  1202. "content": {
  1203. "membership": Membership.INVITE,
  1204. "third_party_invite": third_party_invite,
  1205. },
  1206. "room_id": room_id,
  1207. "sender": sender_user_id,
  1208. "state_key": target_user_id,
  1209. }
  1210. if await self._event_auth_handler.is_host_in_room(room_id, self.hs.hostname):
  1211. room_version_obj = await self.store.get_room_version(room_id)
  1212. builder = self.event_builder_factory.for_room_version(
  1213. room_version_obj, event_dict
  1214. )
  1215. EventValidator().validate_builder(builder)
  1216. # Try several times, it could fail with PartialStateConflictError
  1217. # in send_membership_event, cf comment in except block.
  1218. max_retries = 5
  1219. for i in range(max_retries):
  1220. try:
  1221. (
  1222. event,
  1223. context,
  1224. ) = await self.event_creation_handler.create_new_client_event(
  1225. builder=builder
  1226. )
  1227. event, context = await self.add_display_name_to_third_party_invite(
  1228. room_version_obj, event_dict, event, context
  1229. )
  1230. EventValidator().validate_new(event, self.config)
  1231. # We need to tell the transaction queue to send this out, even
  1232. # though the sender isn't a local user.
  1233. event.internal_metadata.send_on_behalf_of = self.hs.hostname
  1234. try:
  1235. validate_event_for_room_version(event)
  1236. await self._event_auth_handler.check_auth_rules_from_context(
  1237. event
  1238. )
  1239. except AuthError as e:
  1240. logger.warning(
  1241. "Denying new third party invite %r because %s", event, e
  1242. )
  1243. raise e
  1244. await self._check_signature(event, context)
  1245. # We retrieve the room member handler here as to not cause a cyclic dependency
  1246. member_handler = self.hs.get_room_member_handler()
  1247. await member_handler.send_membership_event(None, event, context)
  1248. break
  1249. except PartialStateConflictError as e:
  1250. # Persisting couldn't happen because the room got un-partial stated
  1251. # in the meantime and context needs to be recomputed, so let's do so.
  1252. if i == max_retries - 1:
  1253. raise e
  1254. pass
  1255. else:
  1256. destinations = {x.split(":", 1)[-1] for x in (sender_user_id, room_id)}
  1257. try:
  1258. await self.federation_client.forward_third_party_invite(
  1259. destinations, room_id, event_dict
  1260. )
  1261. except (RequestSendFailed, HttpResponseException):
  1262. raise SynapseError(502, "Failed to forward third party invite")
  1263. async def on_exchange_third_party_invite_request(
  1264. self, event_dict: JsonDict
  1265. ) -> None:
  1266. """Handle an exchange_third_party_invite request from a remote server
  1267. The remote server will call this when it wants to turn a 3pid invite
  1268. into a normal m.room.member invite.
  1269. Args:
  1270. event_dict: Dictionary containing the event body.
  1271. """
  1272. assert_params_in_dict(event_dict, ["room_id"])
  1273. room_version_obj = await self.store.get_room_version(event_dict["room_id"])
  1274. # NB: event_dict has a particular specced format we might need to fudge
  1275. # if we change event formats too much.
  1276. builder = self.event_builder_factory.for_room_version(
  1277. room_version_obj, event_dict
  1278. )
  1279. # Try several times, it could fail with PartialStateConflictError
  1280. # in send_membership_event, cf comment in except block.
  1281. max_retries = 5
  1282. for i in range(max_retries):
  1283. try:
  1284. (
  1285. event,
  1286. context,
  1287. ) = await self.event_creation_handler.create_new_client_event(
  1288. builder=builder
  1289. )
  1290. event, context = await self.add_display_name_to_third_party_invite(
  1291. room_version_obj, event_dict, event, context
  1292. )
  1293. try:
  1294. validate_event_for_room_version(event)
  1295. await self._event_auth_handler.check_auth_rules_from_context(event)
  1296. except AuthError as e:
  1297. logger.warning("Denying third party invite %r because %s", event, e)
  1298. raise e
  1299. await self._check_signature(event, context)
  1300. # We need to tell the transaction queue to send this out, even
  1301. # though the sender isn't a local user.
  1302. event.internal_metadata.send_on_behalf_of = get_domain_from_id(
  1303. event.sender
  1304. )
  1305. # We retrieve the room member handler here as to not cause a cyclic dependency
  1306. member_handler = self.hs.get_room_member_handler()
  1307. await member_handler.send_membership_event(None, event, context)
  1308. break
  1309. except PartialStateConflictError as e:
  1310. # Persisting couldn't happen because the room got un-partial stated
  1311. # in the meantime and context needs to be recomputed, so let's do so.
  1312. if i == max_retries - 1:
  1313. raise e
  1314. pass
  1315. async def add_display_name_to_third_party_invite(
  1316. self,
  1317. room_version_obj: RoomVersion,
  1318. event_dict: JsonDict,
  1319. event: EventBase,
  1320. context: EventContext,
  1321. ) -> Tuple[EventBase, EventContext]:
  1322. key = (
  1323. EventTypes.ThirdPartyInvite,
  1324. event.content["third_party_invite"]["signed"]["token"],
  1325. )
  1326. original_invite = None
  1327. prev_state_ids = await context.get_prev_state_ids(
  1328. StateFilter.from_types([(EventTypes.ThirdPartyInvite, None)])
  1329. )
  1330. original_invite_id = prev_state_ids.get(key)
  1331. if original_invite_id:
  1332. original_invite = await self.store.get_event(
  1333. original_invite_id, allow_none=True
  1334. )
  1335. if original_invite:
  1336. # If the m.room.third_party_invite event's content is empty, it means the
  1337. # invite has been revoked. In this case, we don't have to raise an error here
  1338. # because the auth check will fail on the invite (because it's not able to
  1339. # fetch public keys from the m.room.third_party_invite event's content, which
  1340. # is empty).
  1341. display_name = original_invite.content.get("display_name")
  1342. event_dict["content"]["third_party_invite"]["display_name"] = display_name
  1343. else:
  1344. logger.info(
  1345. "Could not find invite event for third_party_invite: %r", event_dict
  1346. )
  1347. # We don't discard here as this is not the appropriate place to do
  1348. # auth checks. If we need the invite and don't have it then the
  1349. # auth check code will explode appropriately.
  1350. builder = self.event_builder_factory.for_room_version(
  1351. room_version_obj, event_dict
  1352. )
  1353. EventValidator().validate_builder(builder)
  1354. event, context = await self.event_creation_handler.create_new_client_event(
  1355. builder=builder
  1356. )
  1357. EventValidator().validate_new(event, self.config)
  1358. return event, context
  1359. async def _check_signature(self, event: EventBase, context: EventContext) -> None:
  1360. """
  1361. Checks that the signature in the event is consistent with its invite.
  1362. Args:
  1363. event: The m.room.member event to check
  1364. context:
  1365. Raises:
  1366. AuthError: if signature didn't match any keys, or key has been
  1367. revoked,
  1368. SynapseError: if a transient error meant a key couldn't be checked
  1369. for revocation.
  1370. """
  1371. signed = event.content["third_party_invite"]["signed"]
  1372. token = signed["token"]
  1373. prev_state_ids = await context.get_prev_state_ids(
  1374. StateFilter.from_types([(EventTypes.ThirdPartyInvite, None)])
  1375. )
  1376. invite_event_id = prev_state_ids.get((EventTypes.ThirdPartyInvite, token))
  1377. invite_event = None
  1378. if invite_event_id:
  1379. invite_event = await self.store.get_event(invite_event_id, allow_none=True)
  1380. if not invite_event:
  1381. raise AuthError(403, "Could not find invite")
  1382. logger.debug("Checking auth on event %r", event.content)
  1383. last_exception: Optional[Exception] = None
  1384. # for each public key in the 3pid invite event
  1385. for public_key_object in event_auth.get_public_keys(invite_event):
  1386. try:
  1387. # for each sig on the third_party_invite block of the actual invite
  1388. for server, signature_block in signed["signatures"].items():
  1389. for key_name in signature_block.keys():
  1390. if not key_name.startswith("ed25519:"):
  1391. continue
  1392. logger.debug(
  1393. "Attempting to verify sig with key %s from %r "
  1394. "against pubkey %r",
  1395. key_name,
  1396. server,
  1397. public_key_object,
  1398. )
  1399. try:
  1400. public_key = public_key_object["public_key"]
  1401. verify_key = decode_verify_key_bytes(
  1402. key_name, decode_base64(public_key)
  1403. )
  1404. verify_signed_json(signed, server, verify_key)
  1405. logger.debug(
  1406. "Successfully verified sig with key %s from %r "
  1407. "against pubkey %r",
  1408. key_name,
  1409. server,
  1410. public_key_object,
  1411. )
  1412. except Exception:
  1413. logger.info(
  1414. "Failed to verify sig with key %s from %r "
  1415. "against pubkey %r",
  1416. key_name,
  1417. server,
  1418. public_key_object,
  1419. )
  1420. raise
  1421. try:
  1422. if "key_validity_url" in public_key_object:
  1423. await self._check_key_revocation(
  1424. public_key, public_key_object["key_validity_url"]
  1425. )
  1426. except Exception:
  1427. logger.info(
  1428. "Failed to query key_validity_url %s",
  1429. public_key_object["key_validity_url"],
  1430. )
  1431. raise
  1432. return
  1433. except Exception as e:
  1434. last_exception = e
  1435. if last_exception is None:
  1436. # we can only get here if get_public_keys() returned an empty list
  1437. # TODO: make this better
  1438. raise RuntimeError("no public key in invite event")
  1439. raise last_exception
  1440. async def _check_key_revocation(self, public_key: str, url: str) -> None:
  1441. """
  1442. Checks whether public_key has been revoked.
  1443. Args:
  1444. public_key: base-64 encoded public key.
  1445. url: Key revocation URL.
  1446. Raises:
  1447. AuthError: if they key has been revoked.
  1448. SynapseError: if a transient error meant a key couldn't be checked
  1449. for revocation.
  1450. """
  1451. try:
  1452. response = await self.http_client.get_json(url, {"public_key": public_key})
  1453. except Exception:
  1454. raise SynapseError(502, "Third party certificate could not be checked")
  1455. if "valid" not in response or not response["valid"]:
  1456. raise AuthError(403, "Third party certificate was invalid")
  1457. async def _clean_room_for_join(self, room_id: str) -> None:
  1458. """Called to clean up any data in DB for a given room, ready for the
  1459. server to join the room.
  1460. Args:
  1461. room_id
  1462. """
  1463. if self.config.worker.worker_app:
  1464. await self._clean_room_for_join_client(room_id)
  1465. else:
  1466. await self.store.clean_room_for_join(room_id)
  1467. async def get_room_complexity(
  1468. self, remote_room_hosts: List[str], room_id: str
  1469. ) -> Optional[dict]:
  1470. """
  1471. Fetch the complexity of a remote room over federation.
  1472. Args:
  1473. remote_room_hosts: The remote servers to ask.
  1474. room_id: The room ID to ask about.
  1475. Returns:
  1476. Dict contains the complexity
  1477. metric versions, while None means we could not fetch the complexity.
  1478. """
  1479. for host in remote_room_hosts:
  1480. res = await self.federation_client.get_room_complexity(host, room_id)
  1481. # We got a result, return it.
  1482. if res:
  1483. return res
  1484. # We fell off the bottom, couldn't get the complexity from anyone. Oh
  1485. # well.
  1486. return None
  1487. async def _resume_partial_state_room_sync(self) -> None:
  1488. """Resumes resyncing of all partial-state rooms after a restart."""
  1489. assert not self.config.worker.worker_app
  1490. partial_state_rooms = await self.store.get_partial_state_room_resync_info()
  1491. for room_id, resync_info in partial_state_rooms.items():
  1492. self._start_partial_state_room_sync(
  1493. initial_destination=resync_info.joined_via,
  1494. other_destinations=resync_info.servers_in_room,
  1495. room_id=room_id,
  1496. )
  1497. def _start_partial_state_room_sync(
  1498. self,
  1499. initial_destination: Optional[str],
  1500. other_destinations: Collection[str],
  1501. room_id: str,
  1502. ) -> None:
  1503. """Starts the background process to resync the state of a partial state room,
  1504. if it is not already running.
  1505. Args:
  1506. initial_destination: the initial homeserver to pull the state from
  1507. other_destinations: other homeservers to try to pull the state from, if
  1508. `initial_destination` is unavailable
  1509. room_id: room to be resynced
  1510. """
  1511. async def _sync_partial_state_room_wrapper() -> None:
  1512. if room_id in self._active_partial_state_syncs:
  1513. # Another local user has joined the room while there is already a
  1514. # partial state sync running. This implies that there is a new join
  1515. # event to un-partial state. We might find ourselves in one of a few
  1516. # scenarios:
  1517. # 1. There is an existing partial state sync. The partial state sync
  1518. # un-partial states the new join event before completing and all is
  1519. # well.
  1520. # 2. Before the latest join, the homeserver was no longer in the room
  1521. # and there is an existing partial state sync from our previous
  1522. # membership of the room. The partial state sync may have:
  1523. # a) succeeded, but not yet terminated. The room will not be
  1524. # un-partial stated again unless we restart the partial state
  1525. # sync.
  1526. # b) failed, because we were no longer in the room and remote
  1527. # homeservers were refusing our requests, but not yet
  1528. # terminated. After the latest join, remote homeservers may
  1529. # start answering our requests again, so we should restart the
  1530. # partial state sync.
  1531. # In the cases where we would want to restart the partial state sync,
  1532. # the room would have the partial state flag when the partial state sync
  1533. # terminates.
  1534. self._partial_state_syncs_maybe_needing_restart[room_id] = (
  1535. initial_destination,
  1536. other_destinations,
  1537. )
  1538. return
  1539. self._active_partial_state_syncs.add(room_id)
  1540. try:
  1541. await self._sync_partial_state_room(
  1542. initial_destination=initial_destination,
  1543. other_destinations=other_destinations,
  1544. room_id=room_id,
  1545. )
  1546. finally:
  1547. # Read the room's partial state flag while we still hold the claim to
  1548. # being the active partial state sync (so that another partial state
  1549. # sync can't come along and mess with it under us).
  1550. # Normally, the partial state flag will be gone. If it isn't, then we
  1551. # may find ourselves in scenario 2a or 2b as described in the comment
  1552. # above, where we want to restart the partial state sync.
  1553. is_still_partial_state_room = await self.store.is_partial_state_room(
  1554. room_id
  1555. )
  1556. self._active_partial_state_syncs.remove(room_id)
  1557. if room_id in self._partial_state_syncs_maybe_needing_restart:
  1558. (
  1559. restart_initial_destination,
  1560. restart_other_destinations,
  1561. ) = self._partial_state_syncs_maybe_needing_restart.pop(room_id)
  1562. if is_still_partial_state_room:
  1563. self._start_partial_state_room_sync(
  1564. initial_destination=restart_initial_destination,
  1565. other_destinations=restart_other_destinations,
  1566. room_id=room_id,
  1567. )
  1568. run_as_background_process(
  1569. desc="sync_partial_state_room", func=_sync_partial_state_room_wrapper
  1570. )
  1571. async def _sync_partial_state_room(
  1572. self,
  1573. initial_destination: Optional[str],
  1574. other_destinations: Collection[str],
  1575. room_id: str,
  1576. ) -> None:
  1577. """Background process to resync the state of a partial-state room
  1578. Args:
  1579. initial_destination: the initial homeserver to pull the state from
  1580. other_destinations: other homeservers to try to pull the state from, if
  1581. `initial_destination` is unavailable
  1582. room_id: room to be resynced
  1583. """
  1584. # Assume that we run on the main process for now.
  1585. # TODO(faster_joins,multiple workers)
  1586. # When moving the sync to workers, we need to ensure that
  1587. # * `_start_partial_state_room_sync` still prevents duplicate resyncs
  1588. # * `_is_partial_state_room_linearizer` correctly guards partial state flags
  1589. # for rooms between the workers doing remote joins and resync.
  1590. assert not self.config.worker.worker_app
  1591. # TODO(faster_joins): do we need to lock to avoid races? What happens if other
  1592. # worker processes kick off a resync in parallel? Perhaps we should just elect
  1593. # a single worker to do the resync.
  1594. # https://github.com/matrix-org/synapse/issues/12994
  1595. #
  1596. # TODO(faster_joins): what happens if we leave the room during a resync? if we
  1597. # really leave, that might mean we have difficulty getting the room state over
  1598. # federation.
  1599. # https://github.com/matrix-org/synapse/issues/12802
  1600. # Make an infinite iterator of destinations to try. Once we find a working
  1601. # destination, we'll stick with it until it flakes.
  1602. destinations = _prioritise_destinations_for_partial_state_resync(
  1603. initial_destination, other_destinations, room_id
  1604. )
  1605. destination_iter = itertools.cycle(destinations)
  1606. # `destination` is the current remote homeserver we're pulling from.
  1607. destination = next(destination_iter)
  1608. logger.info("Syncing state for room %s via %s", room_id, destination)
  1609. # we work through the queue in order of increasing stream ordering.
  1610. while True:
  1611. batch = await self.store.get_partial_state_events_batch(room_id)
  1612. if not batch:
  1613. # all the events are updated, so we can update current state and
  1614. # clear the lazy-loading flag.
  1615. logger.info("Updating current state for %s", room_id)
  1616. # TODO(faster_joins): notify workers in notify_room_un_partial_stated
  1617. # https://github.com/matrix-org/synapse/issues/12994
  1618. await self.state_handler.update_current_state(room_id)
  1619. logger.info("Handling any pending device list updates")
  1620. await self._device_handler.handle_room_un_partial_stated(room_id)
  1621. async with self._is_partial_state_room_linearizer.queue(room_id):
  1622. logger.info("Clearing partial-state flag for %s", room_id)
  1623. success = await self.store.clear_partial_state_room(room_id)
  1624. # Poke the notifier so that other workers see the write to
  1625. # the un-partial-stated rooms stream.
  1626. self._notifier.notify_replication()
  1627. if success:
  1628. logger.info("State resync complete for %s", room_id)
  1629. self._storage_controllers.state.notify_room_un_partial_stated(
  1630. room_id
  1631. )
  1632. # TODO(faster_joins) update room stats and user directory?
  1633. # https://github.com/matrix-org/synapse/issues/12814
  1634. # https://github.com/matrix-org/synapse/issues/12815
  1635. return
  1636. # we raced against more events arriving with partial state. Go round
  1637. # the loop again. We've already logged a warning, so no need for more.
  1638. continue
  1639. events = await self.store.get_events_as_list(
  1640. batch,
  1641. redact_behaviour=EventRedactBehaviour.as_is,
  1642. allow_rejected=True,
  1643. )
  1644. for event in events:
  1645. for attempt in itertools.count():
  1646. try:
  1647. await self._federation_event_handler.update_state_for_partial_state_event(
  1648. destination, event
  1649. )
  1650. break
  1651. except FederationPullAttemptBackoffError as exc:
  1652. # Log a warning about why we failed to process the event (the error message
  1653. # for `FederationPullAttemptBackoffError` is pretty good)
  1654. logger.warning("_sync_partial_state_room: %s", exc)
  1655. # We do not record a failed pull attempt when we backoff fetching a missing
  1656. # `prev_event` because not being able to fetch the `prev_events` just means
  1657. # we won't be able to de-outlier the pulled event. But we can still use an
  1658. # `outlier` in the state/auth chain for another event. So we shouldn't stop
  1659. # a downstream event from trying to pull it.
  1660. #
  1661. # This avoids a cascade of backoff for all events in the DAG downstream from
  1662. # one event backoff upstream.
  1663. except FederationError as e:
  1664. # TODO: We should `record_event_failed_pull_attempt` here,
  1665. # see https://github.com/matrix-org/synapse/issues/13700
  1666. if attempt == len(destinations) - 1:
  1667. # We have tried every remote server for this event. Give up.
  1668. # TODO(faster_joins) giving up isn't the right thing to do
  1669. # if there's a temporary network outage. retrying
  1670. # indefinitely is also not the right thing to do if we can
  1671. # reach all homeservers and they all claim they don't have
  1672. # the state we want.
  1673. # https://github.com/matrix-org/synapse/issues/13000
  1674. logger.error(
  1675. "Failed to get state for %s at %s from %s because %s, "
  1676. "giving up!",
  1677. room_id,
  1678. event,
  1679. destination,
  1680. e,
  1681. )
  1682. raise
  1683. # Try the next remote server.
  1684. logger.info(
  1685. "Failed to get state for %s at %s from %s because %s",
  1686. room_id,
  1687. event,
  1688. destination,
  1689. e,
  1690. )
  1691. destination = next(destination_iter)
  1692. logger.info(
  1693. "Syncing state for room %s via %s instead",
  1694. room_id,
  1695. destination,
  1696. )
  1697. def _prioritise_destinations_for_partial_state_resync(
  1698. initial_destination: Optional[str],
  1699. other_destinations: Collection[str],
  1700. room_id: str,
  1701. ) -> Collection[str]:
  1702. """Work out the order in which we should ask servers to resync events.
  1703. If an `initial_destination` is given, it takes top priority. Otherwise
  1704. all servers are treated equally.
  1705. :raises ValueError: if no destination is provided at all.
  1706. """
  1707. if initial_destination is None and len(other_destinations) == 0:
  1708. raise ValueError(f"Cannot resync state of {room_id}: no destinations provided")
  1709. if initial_destination is None:
  1710. return other_destinations
  1711. # Move `initial_destination` to the front of the list.
  1712. destinations = list(other_destinations)
  1713. if initial_destination in destinations:
  1714. destinations.remove(initial_destination)
  1715. destinations = [initial_destination] + destinations
  1716. return destinations