Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

3018 wiersze
115 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017-2018 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """Contains handlers for federation events."""
  18. import itertools
  19. import logging
  20. from collections.abc import Container
  21. from http import HTTPStatus
  22. from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
  23. import attr
  24. from signedjson.key import decode_verify_key_bytes
  25. from signedjson.sign import verify_signed_json
  26. from unpaddedbase64 import decode_base64
  27. from twisted.internet import defer
  28. from synapse import event_auth
  29. from synapse.api.constants import (
  30. EventTypes,
  31. Membership,
  32. RejectedReason,
  33. RoomEncryptionAlgorithms,
  34. )
  35. from synapse.api.errors import (
  36. AuthError,
  37. CodeMessageException,
  38. Codes,
  39. FederationDeniedError,
  40. FederationError,
  41. HttpResponseException,
  42. NotFoundError,
  43. RequestSendFailed,
  44. SynapseError,
  45. )
  46. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion, RoomVersions
  47. from synapse.crypto.event_signing import compute_event_signature
  48. from synapse.event_auth import auth_types_for_event
  49. from synapse.events import EventBase
  50. from synapse.events.snapshot import EventContext
  51. from synapse.events.validator import EventValidator
  52. from synapse.handlers._base import BaseHandler
  53. from synapse.logging.context import (
  54. make_deferred_yieldable,
  55. nested_logging_context,
  56. preserve_fn,
  57. run_in_background,
  58. )
  59. from synapse.logging.utils import log_function
  60. from synapse.metrics.background_process_metrics import run_as_background_process
  61. from synapse.replication.http.devices import ReplicationUserDevicesResyncRestServlet
  62. from synapse.replication.http.federation import (
  63. ReplicationCleanRoomRestServlet,
  64. ReplicationFederationSendEventsRestServlet,
  65. ReplicationStoreRoomOnInviteRestServlet,
  66. )
  67. from synapse.replication.http.membership import ReplicationUserJoinedLeftRoomRestServlet
  68. from synapse.state import StateResolutionStore, resolve_events_with_store
  69. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  70. from synapse.types import JsonDict, StateMap, UserID, get_domain_from_id
  71. from synapse.util.async_helpers import Linearizer, concurrently_execute
  72. from synapse.util.distributor import user_joined_room
  73. from synapse.util.retryutils import NotRetryingDestination
  74. from synapse.util.stringutils import shortstr
  75. from synapse.visibility import filter_events_for_server
  76. logger = logging.getLogger(__name__)
  77. @attr.s
  78. class _NewEventInfo:
  79. """Holds information about a received event, ready for passing to _handle_new_events
  80. Attributes:
  81. event: the received event
  82. state: the state at that event
  83. auth_events: the auth_event map for that event
  84. """
  85. event = attr.ib(type=EventBase)
  86. state = attr.ib(type=Optional[Sequence[EventBase]], default=None)
  87. auth_events = attr.ib(type=Optional[StateMap[EventBase]], default=None)
  88. class FederationHandler(BaseHandler):
  89. """Handles events that originated from federation.
  90. Responsible for:
  91. a) handling received Pdus before handing them on as Events to the rest
  92. of the homeserver (including auth and state conflict resoultion)
  93. b) converting events that were produced by local clients that may need
  94. to be sent to remote homeservers.
  95. c) doing the necessary dances to invite remote users and join remote
  96. rooms.
  97. """
  98. def __init__(self, hs):
  99. super(FederationHandler, self).__init__(hs)
  100. self.hs = hs
  101. self.store = hs.get_datastore()
  102. self.storage = hs.get_storage()
  103. self.state_store = self.storage.state
  104. self.federation_client = hs.get_federation_client()
  105. self.state_handler = hs.get_state_handler()
  106. self.server_name = hs.hostname
  107. self.keyring = hs.get_keyring()
  108. self.action_generator = hs.get_action_generator()
  109. self.is_mine_id = hs.is_mine_id
  110. self.pusher_pool = hs.get_pusherpool()
  111. self.spam_checker = hs.get_spam_checker()
  112. self.event_creation_handler = hs.get_event_creation_handler()
  113. self._message_handler = hs.get_message_handler()
  114. self._server_notices_mxid = hs.config.server_notices_mxid
  115. self.config = hs.config
  116. self.http_client = hs.get_simple_http_client()
  117. self._instance_name = hs.get_instance_name()
  118. self._replication = hs.get_replication_data_handler()
  119. self._send_events = ReplicationFederationSendEventsRestServlet.make_client(hs)
  120. self._notify_user_membership_change = ReplicationUserJoinedLeftRoomRestServlet.make_client(
  121. hs
  122. )
  123. self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(
  124. hs
  125. )
  126. if hs.config.worker_app:
  127. self._user_device_resync = ReplicationUserDevicesResyncRestServlet.make_client(
  128. hs
  129. )
  130. self._maybe_store_room_on_invite = ReplicationStoreRoomOnInviteRestServlet.make_client(
  131. hs
  132. )
  133. else:
  134. self._device_list_updater = hs.get_device_handler().device_list_updater
  135. self._maybe_store_room_on_invite = self.store.maybe_store_room_on_invite
  136. # When joining a room we need to queue any events for that room up
  137. self.room_queues = {}
  138. self._room_pdu_linearizer = Linearizer("fed_room_pdu")
  139. self.third_party_event_rules = hs.get_third_party_event_rules()
  140. self._ephemeral_messages_enabled = hs.config.enable_ephemeral_messages
  141. async def on_receive_pdu(self, origin, pdu, sent_to_us_directly=False) -> None:
  142. """ Process a PDU received via a federation /send/ transaction, or
  143. via backfill of missing prev_events
  144. Args:
  145. origin (str): server which initiated the /send/ transaction. Will
  146. be used to fetch missing events or state.
  147. pdu (FrozenEvent): received PDU
  148. sent_to_us_directly (bool): True if this event was pushed to us; False if
  149. we pulled it as the result of a missing prev_event.
  150. """
  151. room_id = pdu.room_id
  152. event_id = pdu.event_id
  153. logger.info("handling received PDU: %s", pdu)
  154. # We reprocess pdus when we have seen them only as outliers
  155. existing = await self.store.get_event(
  156. event_id, allow_none=True, allow_rejected=True
  157. )
  158. # FIXME: Currently we fetch an event again when we already have it
  159. # if it has been marked as an outlier.
  160. already_seen = existing and (
  161. not existing.internal_metadata.is_outlier()
  162. or pdu.internal_metadata.is_outlier()
  163. )
  164. if already_seen:
  165. logger.debug("[%s %s]: Already seen pdu", room_id, event_id)
  166. return
  167. # do some initial sanity-checking of the event. In particular, make
  168. # sure it doesn't have hundreds of prev_events or auth_events, which
  169. # could cause a huge state resolution or cascade of event fetches.
  170. try:
  171. self._sanity_check_event(pdu)
  172. except SynapseError as err:
  173. logger.warning(
  174. "[%s %s] Received event failed sanity checks", room_id, event_id
  175. )
  176. raise FederationError("ERROR", err.code, err.msg, affected=pdu.event_id)
  177. # If we are currently in the process of joining this room, then we
  178. # queue up events for later processing.
  179. if room_id in self.room_queues:
  180. logger.info(
  181. "[%s %s] Queuing PDU from %s for now: join in progress",
  182. room_id,
  183. event_id,
  184. origin,
  185. )
  186. self.room_queues[room_id].append((pdu, origin))
  187. return
  188. # If we're not in the room just ditch the event entirely. This is
  189. # probably an old server that has come back and thinks we're still in
  190. # the room (or we've been rejoined to the room by a state reset).
  191. #
  192. # Note that if we were never in the room then we would have already
  193. # dropped the event, since we wouldn't know the room version.
  194. is_in_room = await self.auth.check_host_in_room(room_id, self.server_name)
  195. if not is_in_room:
  196. logger.info(
  197. "[%s %s] Ignoring PDU from %s as we're not in the room",
  198. room_id,
  199. event_id,
  200. origin,
  201. )
  202. return None
  203. state = None
  204. # Get missing pdus if necessary.
  205. if not pdu.internal_metadata.is_outlier():
  206. # We only backfill backwards to the min depth.
  207. min_depth = await self.get_min_depth_for_context(pdu.room_id)
  208. logger.debug("[%s %s] min_depth: %d", room_id, event_id, min_depth)
  209. prevs = set(pdu.prev_event_ids())
  210. seen = await self.store.have_events_in_timeline(prevs)
  211. if min_depth is not None and pdu.depth < min_depth:
  212. # This is so that we don't notify the user about this
  213. # message, to work around the fact that some events will
  214. # reference really really old events we really don't want to
  215. # send to the clients.
  216. pdu.internal_metadata.outlier = True
  217. elif min_depth is not None and pdu.depth > min_depth:
  218. missing_prevs = prevs - seen
  219. if sent_to_us_directly and missing_prevs:
  220. # If we're missing stuff, ensure we only fetch stuff one
  221. # at a time.
  222. logger.info(
  223. "[%s %s] Acquiring room lock to fetch %d missing prev_events: %s",
  224. room_id,
  225. event_id,
  226. len(missing_prevs),
  227. shortstr(missing_prevs),
  228. )
  229. with (await self._room_pdu_linearizer.queue(pdu.room_id)):
  230. logger.info(
  231. "[%s %s] Acquired room lock to fetch %d missing prev_events",
  232. room_id,
  233. event_id,
  234. len(missing_prevs),
  235. )
  236. try:
  237. await self._get_missing_events_for_pdu(
  238. origin, pdu, prevs, min_depth
  239. )
  240. except Exception as e:
  241. raise Exception(
  242. "Error fetching missing prev_events for %s: %s"
  243. % (event_id, e)
  244. )
  245. # Update the set of things we've seen after trying to
  246. # fetch the missing stuff
  247. seen = await self.store.have_events_in_timeline(prevs)
  248. if not prevs - seen:
  249. logger.info(
  250. "[%s %s] Found all missing prev_events",
  251. room_id,
  252. event_id,
  253. )
  254. if prevs - seen:
  255. # We've still not been able to get all of the prev_events for this event.
  256. #
  257. # In this case, we need to fall back to asking another server in the
  258. # federation for the state at this event. That's ok provided we then
  259. # resolve the state against other bits of the DAG before using it (which
  260. # will ensure that you can't just take over a room by sending an event,
  261. # withholding its prev_events, and declaring yourself to be an admin in
  262. # the subsequent state request).
  263. #
  264. # Now, if we're pulling this event as a missing prev_event, then clearly
  265. # this event is not going to become the only forward-extremity and we are
  266. # guaranteed to resolve its state against our existing forward
  267. # extremities, so that should be fine.
  268. #
  269. # On the other hand, if this event was pushed to us, it is possible for
  270. # it to become the only forward-extremity in the room, and we would then
  271. # trust its state to be the state for the whole room. This is very bad.
  272. # Further, if the event was pushed to us, there is no excuse for us not to
  273. # have all the prev_events. We therefore reject any such events.
  274. #
  275. # XXX this really feels like it could/should be merged with the above,
  276. # but there is an interaction with min_depth that I'm not really
  277. # following.
  278. if sent_to_us_directly:
  279. logger.warning(
  280. "[%s %s] Rejecting: failed to fetch %d prev events: %s",
  281. room_id,
  282. event_id,
  283. len(prevs - seen),
  284. shortstr(prevs - seen),
  285. )
  286. raise FederationError(
  287. "ERROR",
  288. 403,
  289. (
  290. "Your server isn't divulging details about prev_events "
  291. "referenced in this event."
  292. ),
  293. affected=pdu.event_id,
  294. )
  295. logger.info(
  296. "Event %s is missing prev_events: calculating state for a "
  297. "backwards extremity",
  298. event_id,
  299. )
  300. # Calculate the state after each of the previous events, and
  301. # resolve them to find the correct state at the current event.
  302. event_map = {event_id: pdu}
  303. try:
  304. # Get the state of the events we know about
  305. ours = await self.state_store.get_state_groups_ids(room_id, seen)
  306. # state_maps is a list of mappings from (type, state_key) to event_id
  307. state_maps = list(ours.values()) # type: List[StateMap[str]]
  308. # we don't need this any more, let's delete it.
  309. del ours
  310. # Ask the remote server for the states we don't
  311. # know about
  312. for p in prevs - seen:
  313. logger.info(
  314. "Requesting state at missing prev_event %s", event_id,
  315. )
  316. with nested_logging_context(p):
  317. # note that if any of the missing prevs share missing state or
  318. # auth events, the requests to fetch those events are deduped
  319. # by the get_pdu_cache in federation_client.
  320. (remote_state, _,) = await self._get_state_for_room(
  321. origin, room_id, p, include_event_in_state=True
  322. )
  323. remote_state_map = {
  324. (x.type, x.state_key): x.event_id for x in remote_state
  325. }
  326. state_maps.append(remote_state_map)
  327. for x in remote_state:
  328. event_map[x.event_id] = x
  329. room_version = await self.store.get_room_version_id(room_id)
  330. state_map = await resolve_events_with_store(
  331. self.clock,
  332. room_id,
  333. room_version,
  334. state_maps,
  335. event_map,
  336. state_res_store=StateResolutionStore(self.store),
  337. )
  338. # We need to give _process_received_pdu the actual state events
  339. # rather than event ids, so generate that now.
  340. # First though we need to fetch all the events that are in
  341. # state_map, so we can build up the state below.
  342. evs = await self.store.get_events(
  343. list(state_map.values()),
  344. get_prev_content=False,
  345. redact_behaviour=EventRedactBehaviour.AS_IS,
  346. )
  347. event_map.update(evs)
  348. state = [event_map[e] for e in state_map.values()]
  349. except Exception:
  350. logger.warning(
  351. "[%s %s] Error attempting to resolve state at missing "
  352. "prev_events",
  353. room_id,
  354. event_id,
  355. exc_info=True,
  356. )
  357. raise FederationError(
  358. "ERROR",
  359. 403,
  360. "We can't get valid state history.",
  361. affected=event_id,
  362. )
  363. await self._process_received_pdu(origin, pdu, state=state)
  364. async def _get_missing_events_for_pdu(self, origin, pdu, prevs, min_depth):
  365. """
  366. Args:
  367. origin (str): Origin of the pdu. Will be called to get the missing events
  368. pdu: received pdu
  369. prevs (set(str)): List of event ids which we are missing
  370. min_depth (int): Minimum depth of events to return.
  371. """
  372. room_id = pdu.room_id
  373. event_id = pdu.event_id
  374. seen = await self.store.have_events_in_timeline(prevs)
  375. if not prevs - seen:
  376. return
  377. latest = await self.store.get_latest_event_ids_in_room(room_id)
  378. # We add the prev events that we have seen to the latest
  379. # list to ensure the remote server doesn't give them to us
  380. latest = set(latest)
  381. latest |= seen
  382. logger.info(
  383. "[%s %s]: Requesting missing events between %s and %s",
  384. room_id,
  385. event_id,
  386. shortstr(latest),
  387. event_id,
  388. )
  389. # XXX: we set timeout to 10s to help workaround
  390. # https://github.com/matrix-org/synapse/issues/1733.
  391. # The reason is to avoid holding the linearizer lock
  392. # whilst processing inbound /send transactions, causing
  393. # FDs to stack up and block other inbound transactions
  394. # which empirically can currently take up to 30 minutes.
  395. #
  396. # N.B. this explicitly disables retry attempts.
  397. #
  398. # N.B. this also increases our chances of falling back to
  399. # fetching fresh state for the room if the missing event
  400. # can't be found, which slightly reduces our security.
  401. # it may also increase our DAG extremity count for the room,
  402. # causing additional state resolution? See #1760.
  403. # However, fetching state doesn't hold the linearizer lock
  404. # apparently.
  405. #
  406. # see https://github.com/matrix-org/synapse/pull/1744
  407. #
  408. # ----
  409. #
  410. # Update richvdh 2018/09/18: There are a number of problems with timing this
  411. # request out agressively on the client side:
  412. #
  413. # - it plays badly with the server-side rate-limiter, which starts tarpitting you
  414. # if you send too many requests at once, so you end up with the server carefully
  415. # working through the backlog of your requests, which you have already timed
  416. # out.
  417. #
  418. # - for this request in particular, we now (as of
  419. # https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the
  420. # server can't produce a plausible-looking set of prev_events - so we becone
  421. # much more likely to reject the event.
  422. #
  423. # - contrary to what it says above, we do *not* fall back to fetching fresh state
  424. # for the room if get_missing_events times out. Rather, we give up processing
  425. # the PDU whose prevs we are missing, which then makes it much more likely that
  426. # we'll end up back here for the *next* PDU in the list, which exacerbates the
  427. # problem.
  428. #
  429. # - the agressive 10s timeout was introduced to deal with incoming federation
  430. # requests taking 8 hours to process. It's not entirely clear why that was going
  431. # on; certainly there were other issues causing traffic storms which are now
  432. # resolved, and I think in any case we may be more sensible about our locking
  433. # now. We're *certainly* more sensible about our logging.
  434. #
  435. # All that said: Let's try increasing the timout to 60s and see what happens.
  436. try:
  437. missing_events = await self.federation_client.get_missing_events(
  438. origin,
  439. room_id,
  440. earliest_events_ids=list(latest),
  441. latest_events=[pdu],
  442. limit=10,
  443. min_depth=min_depth,
  444. timeout=60000,
  445. )
  446. except (RequestSendFailed, HttpResponseException, NotRetryingDestination) as e:
  447. # We failed to get the missing events, but since we need to handle
  448. # the case of `get_missing_events` not returning the necessary
  449. # events anyway, it is safe to simply log the error and continue.
  450. logger.warning(
  451. "[%s %s]: Failed to get prev_events: %s", room_id, event_id, e
  452. )
  453. return
  454. logger.info(
  455. "[%s %s]: Got %d prev_events: %s",
  456. room_id,
  457. event_id,
  458. len(missing_events),
  459. shortstr(missing_events),
  460. )
  461. # We want to sort these by depth so we process them and
  462. # tell clients about them in order.
  463. missing_events.sort(key=lambda x: x.depth)
  464. for ev in missing_events:
  465. logger.info(
  466. "[%s %s] Handling received prev_event %s",
  467. room_id,
  468. event_id,
  469. ev.event_id,
  470. )
  471. with nested_logging_context(ev.event_id):
  472. try:
  473. await self.on_receive_pdu(origin, ev, sent_to_us_directly=False)
  474. except FederationError as e:
  475. if e.code == 403:
  476. logger.warning(
  477. "[%s %s] Received prev_event %s failed history check.",
  478. room_id,
  479. event_id,
  480. ev.event_id,
  481. )
  482. else:
  483. raise
  484. async def _get_state_for_room(
  485. self,
  486. destination: str,
  487. room_id: str,
  488. event_id: str,
  489. include_event_in_state: bool = False,
  490. ) -> Tuple[List[EventBase], List[EventBase]]:
  491. """Requests all of the room state at a given event from a remote homeserver.
  492. Args:
  493. destination: The remote homeserver to query for the state.
  494. room_id: The id of the room we're interested in.
  495. event_id: The id of the event we want the state at.
  496. include_event_in_state: if true, the event itself will be included in the
  497. returned state event list.
  498. Returns:
  499. A list of events in the state, possibly including the event itself, and
  500. a list of events in the auth chain for the given event.
  501. """
  502. (
  503. state_event_ids,
  504. auth_event_ids,
  505. ) = await self.federation_client.get_room_state_ids(
  506. destination, room_id, event_id=event_id
  507. )
  508. desired_events = set(state_event_ids + auth_event_ids)
  509. if include_event_in_state:
  510. desired_events.add(event_id)
  511. event_map = await self._get_events_from_store_or_dest(
  512. destination, room_id, desired_events
  513. )
  514. failed_to_fetch = desired_events - event_map.keys()
  515. if failed_to_fetch:
  516. logger.warning(
  517. "Failed to fetch missing state/auth events for %s %s",
  518. event_id,
  519. failed_to_fetch,
  520. )
  521. remote_state = [
  522. event_map[e_id] for e_id in state_event_ids if e_id in event_map
  523. ]
  524. if include_event_in_state:
  525. remote_event = event_map.get(event_id)
  526. if not remote_event:
  527. raise Exception("Unable to get missing prev_event %s" % (event_id,))
  528. if remote_event.is_state() and remote_event.rejected_reason is None:
  529. remote_state.append(remote_event)
  530. auth_chain = [event_map[e_id] for e_id in auth_event_ids if e_id in event_map]
  531. auth_chain.sort(key=lambda e: e.depth)
  532. return remote_state, auth_chain
  533. async def _get_events_from_store_or_dest(
  534. self, destination: str, room_id: str, event_ids: Iterable[str]
  535. ) -> Dict[str, EventBase]:
  536. """Fetch events from a remote destination, checking if we already have them.
  537. Persists any events we don't already have as outliers.
  538. If we fail to fetch any of the events, a warning will be logged, and the event
  539. will be omitted from the result. Likewise, any events which turn out not to
  540. be in the given room.
  541. This function *does not* automatically get missing auth events of the
  542. newly fetched events. Callers must include the full auth chain of
  543. of the missing events in the `event_ids` argument, to ensure that any
  544. missing auth events are correctly fetched.
  545. Returns:
  546. map from event_id to event
  547. """
  548. fetched_events = await self.store.get_events(event_ids, allow_rejected=True)
  549. missing_events = set(event_ids) - fetched_events.keys()
  550. if missing_events:
  551. logger.debug(
  552. "Fetching unknown state/auth events %s for room %s",
  553. missing_events,
  554. room_id,
  555. )
  556. await self._get_events_and_persist(
  557. destination=destination, room_id=room_id, events=missing_events
  558. )
  559. # we need to make sure we re-load from the database to get the rejected
  560. # state correct.
  561. fetched_events.update(
  562. (await self.store.get_events(missing_events, allow_rejected=True))
  563. )
  564. # check for events which were in the wrong room.
  565. #
  566. # this can happen if a remote server claims that the state or
  567. # auth_events at an event in room A are actually events in room B
  568. bad_events = [
  569. (event_id, event.room_id)
  570. for event_id, event in fetched_events.items()
  571. if event.room_id != room_id
  572. ]
  573. for bad_event_id, bad_room_id in bad_events:
  574. # This is a bogus situation, but since we may only discover it a long time
  575. # after it happened, we try our best to carry on, by just omitting the
  576. # bad events from the returned auth/state set.
  577. logger.warning(
  578. "Remote server %s claims event %s in room %s is an auth/state "
  579. "event in room %s",
  580. destination,
  581. bad_event_id,
  582. bad_room_id,
  583. room_id,
  584. )
  585. del fetched_events[bad_event_id]
  586. return fetched_events
  587. async def _process_received_pdu(
  588. self, origin: str, event: EventBase, state: Optional[Iterable[EventBase]],
  589. ):
  590. """ Called when we have a new pdu. We need to do auth checks and put it
  591. through the StateHandler.
  592. Args:
  593. origin: server sending the event
  594. event: event to be persisted
  595. state: Normally None, but if we are handling a gap in the graph
  596. (ie, we are missing one or more prev_events), the resolved state at the
  597. event
  598. """
  599. room_id = event.room_id
  600. event_id = event.event_id
  601. logger.debug("[%s %s] Processing event: %s", room_id, event_id, event)
  602. try:
  603. context = await self._handle_new_event(origin, event, state=state)
  604. except AuthError as e:
  605. raise FederationError("ERROR", e.code, e.msg, affected=event.event_id)
  606. if event.type == EventTypes.Member:
  607. if event.membership == Membership.JOIN:
  608. # Only fire user_joined_room if the user has acutally
  609. # joined the room. Don't bother if the user is just
  610. # changing their profile info.
  611. newly_joined = True
  612. prev_state_ids = await context.get_prev_state_ids()
  613. prev_state_id = prev_state_ids.get((event.type, event.state_key))
  614. if prev_state_id:
  615. prev_state = await self.store.get_event(
  616. prev_state_id, allow_none=True
  617. )
  618. if prev_state and prev_state.membership == Membership.JOIN:
  619. newly_joined = False
  620. if newly_joined:
  621. user = UserID.from_string(event.state_key)
  622. await self.user_joined_room(user, room_id)
  623. # For encrypted messages we check that we know about the sending device,
  624. # if we don't then we mark the device cache for that user as stale.
  625. if event.type == EventTypes.Encrypted:
  626. device_id = event.content.get("device_id")
  627. sender_key = event.content.get("sender_key")
  628. cached_devices = await self.store.get_cached_devices_for_user(event.sender)
  629. resync = False # Whether we should resync device lists.
  630. device = None
  631. if device_id is not None:
  632. device = cached_devices.get(device_id)
  633. if device is None:
  634. logger.info(
  635. "Received event from remote device not in our cache: %s %s",
  636. event.sender,
  637. device_id,
  638. )
  639. resync = True
  640. # We also check if the `sender_key` matches what we expect.
  641. if sender_key is not None:
  642. # Figure out what sender key we're expecting. If we know the
  643. # device and recognize the algorithm then we can work out the
  644. # exact key to expect. Otherwise check it matches any key we
  645. # have for that device.
  646. current_keys = [] # type: Container[str]
  647. if device:
  648. keys = device.get("keys", {}).get("keys", {})
  649. if (
  650. event.content.get("algorithm")
  651. == RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2
  652. ):
  653. # For this algorithm we expect a curve25519 key.
  654. key_name = "curve25519:%s" % (device_id,)
  655. current_keys = [keys.get(key_name)]
  656. else:
  657. # We don't know understand the algorithm, so we just
  658. # check it matches a key for the device.
  659. current_keys = keys.values()
  660. elif device_id:
  661. # We don't have any keys for the device ID.
  662. pass
  663. else:
  664. # The event didn't include a device ID, so we just look for
  665. # keys across all devices.
  666. current_keys = [
  667. key
  668. for device in cached_devices
  669. for key in device.get("keys", {}).get("keys", {}).values()
  670. ]
  671. # We now check that the sender key matches (one of) the expected
  672. # keys.
  673. if sender_key not in current_keys:
  674. logger.info(
  675. "Received event from remote device with unexpected sender key: %s %s: %s",
  676. event.sender,
  677. device_id or "<no device_id>",
  678. sender_key,
  679. )
  680. resync = True
  681. if resync:
  682. run_as_background_process(
  683. "resync_device_due_to_pdu", self._resync_device, event.sender
  684. )
  685. async def _resync_device(self, sender: str) -> None:
  686. """We have detected that the device list for the given user may be out
  687. of sync, so we try and resync them.
  688. """
  689. try:
  690. await self.store.mark_remote_user_device_cache_as_stale(sender)
  691. # Immediately attempt a resync in the background
  692. if self.config.worker_app:
  693. await self._user_device_resync(user_id=sender)
  694. else:
  695. await self._device_list_updater.user_device_resync(sender)
  696. except Exception:
  697. logger.exception("Failed to resync device for %s", sender)
  698. @log_function
  699. async def backfill(self, dest, room_id, limit, extremities):
  700. """ Trigger a backfill request to `dest` for the given `room_id`
  701. This will attempt to get more events from the remote. If the other side
  702. has no new events to offer, this will return an empty list.
  703. As the events are received, we check their signatures, and also do some
  704. sanity-checking on them. If any of the backfilled events are invalid,
  705. this method throws a SynapseError.
  706. TODO: make this more useful to distinguish failures of the remote
  707. server from invalid events (there is probably no point in trying to
  708. re-fetch invalid events from every other HS in the room.)
  709. """
  710. if dest == self.server_name:
  711. raise SynapseError(400, "Can't backfill from self.")
  712. events = await self.federation_client.backfill(
  713. dest, room_id, limit=limit, extremities=extremities
  714. )
  715. # ideally we'd sanity check the events here for excess prev_events etc,
  716. # but it's hard to reject events at this point without completely
  717. # breaking backfill in the same way that it is currently broken by
  718. # events whose signature we cannot verify (#3121).
  719. #
  720. # So for now we accept the events anyway. #3124 tracks this.
  721. #
  722. # for ev in events:
  723. # self._sanity_check_event(ev)
  724. # Don't bother processing events we already have.
  725. seen_events = await self.store.have_events_in_timeline(
  726. {e.event_id for e in events}
  727. )
  728. events = [e for e in events if e.event_id not in seen_events]
  729. if not events:
  730. return []
  731. event_map = {e.event_id: e for e in events}
  732. event_ids = {e.event_id for e in events}
  733. # build a list of events whose prev_events weren't in the batch.
  734. # (XXX: this will include events whose prev_events we already have; that doesn't
  735. # sound right?)
  736. edges = [ev.event_id for ev in events if set(ev.prev_event_ids()) - event_ids]
  737. logger.info("backfill: Got %d events with %d edges", len(events), len(edges))
  738. # For each edge get the current state.
  739. auth_events = {}
  740. state_events = {}
  741. events_to_state = {}
  742. for e_id in edges:
  743. state, auth = await self._get_state_for_room(
  744. destination=dest,
  745. room_id=room_id,
  746. event_id=e_id,
  747. include_event_in_state=False,
  748. )
  749. auth_events.update({a.event_id: a for a in auth})
  750. auth_events.update({s.event_id: s for s in state})
  751. state_events.update({s.event_id: s for s in state})
  752. events_to_state[e_id] = state
  753. required_auth = {
  754. a_id
  755. for event in events
  756. + list(state_events.values())
  757. + list(auth_events.values())
  758. for a_id in event.auth_event_ids()
  759. }
  760. auth_events.update(
  761. {e_id: event_map[e_id] for e_id in required_auth if e_id in event_map}
  762. )
  763. ev_infos = []
  764. # Step 1: persist the events in the chunk we fetched state for (i.e.
  765. # the backwards extremities), with custom auth events and state
  766. for e_id in events_to_state:
  767. # For paranoia we ensure that these events are marked as
  768. # non-outliers
  769. ev = event_map[e_id]
  770. assert not ev.internal_metadata.is_outlier()
  771. ev_infos.append(
  772. _NewEventInfo(
  773. event=ev,
  774. state=events_to_state[e_id],
  775. auth_events={
  776. (
  777. auth_events[a_id].type,
  778. auth_events[a_id].state_key,
  779. ): auth_events[a_id]
  780. for a_id in ev.auth_event_ids()
  781. if a_id in auth_events
  782. },
  783. )
  784. )
  785. await self._handle_new_events(dest, ev_infos, backfilled=True)
  786. # Step 2: Persist the rest of the events in the chunk one by one
  787. events.sort(key=lambda e: e.depth)
  788. for event in events:
  789. if event in events_to_state:
  790. continue
  791. # For paranoia we ensure that these events are marked as
  792. # non-outliers
  793. assert not event.internal_metadata.is_outlier()
  794. # We store these one at a time since each event depends on the
  795. # previous to work out the state.
  796. # TODO: We can probably do something more clever here.
  797. await self._handle_new_event(dest, event, backfilled=True)
  798. return events
  799. async def maybe_backfill(self, room_id, current_depth):
  800. """Checks the database to see if we should backfill before paginating,
  801. and if so do.
  802. """
  803. extremities = await self.store.get_oldest_events_with_depth_in_room(room_id)
  804. if not extremities:
  805. logger.debug("Not backfilling as no extremeties found.")
  806. return
  807. # We only want to paginate if we can actually see the events we'll get,
  808. # as otherwise we'll just spend a lot of resources to get redacted
  809. # events.
  810. #
  811. # We do this by filtering all the backwards extremities and seeing if
  812. # any remain. Given we don't have the extremity events themselves, we
  813. # need to actually check the events that reference them.
  814. #
  815. # *Note*: the spec wants us to keep backfilling until we reach the start
  816. # of the room in case we are allowed to see some of the history. However
  817. # in practice that causes more issues than its worth, as a) its
  818. # relatively rare for there to be any visible history and b) even when
  819. # there is its often sufficiently long ago that clients would stop
  820. # attempting to paginate before backfill reached the visible history.
  821. #
  822. # TODO: If we do do a backfill then we should filter the backwards
  823. # extremities to only include those that point to visible portions of
  824. # history.
  825. #
  826. # TODO: Correctly handle the case where we are allowed to see the
  827. # forward event but not the backward extremity, e.g. in the case of
  828. # initial join of the server where we are allowed to see the join
  829. # event but not anything before it. This would require looking at the
  830. # state *before* the event, ignoring the special casing certain event
  831. # types have.
  832. forward_events = await self.store.get_successor_events(list(extremities))
  833. extremities_events = await self.store.get_events(
  834. forward_events,
  835. redact_behaviour=EventRedactBehaviour.AS_IS,
  836. get_prev_content=False,
  837. )
  838. # We set `check_history_visibility_only` as we might otherwise get false
  839. # positives from users having been erased.
  840. filtered_extremities = await filter_events_for_server(
  841. self.storage,
  842. self.server_name,
  843. list(extremities_events.values()),
  844. redact=False,
  845. check_history_visibility_only=True,
  846. )
  847. if not filtered_extremities:
  848. return False
  849. # Check if we reached a point where we should start backfilling.
  850. sorted_extremeties_tuple = sorted(extremities.items(), key=lambda e: -int(e[1]))
  851. max_depth = sorted_extremeties_tuple[0][1]
  852. # We don't want to specify too many extremities as it causes the backfill
  853. # request URI to be too long.
  854. extremities = dict(sorted_extremeties_tuple[:5])
  855. if current_depth > max_depth:
  856. logger.debug(
  857. "Not backfilling as we don't need to. %d < %d", max_depth, current_depth
  858. )
  859. return
  860. # Now we need to decide which hosts to hit first.
  861. # First we try hosts that are already in the room
  862. # TODO: HEURISTIC ALERT.
  863. curr_state = await self.state_handler.get_current_state(room_id)
  864. def get_domains_from_state(state):
  865. """Get joined domains from state
  866. Args:
  867. state (dict[tuple, FrozenEvent]): State map from type/state
  868. key to event.
  869. Returns:
  870. list[tuple[str, int]]: Returns a list of servers with the
  871. lowest depth of their joins. Sorted by lowest depth first.
  872. """
  873. joined_users = [
  874. (state_key, int(event.depth))
  875. for (e_type, state_key), event in state.items()
  876. if e_type == EventTypes.Member and event.membership == Membership.JOIN
  877. ]
  878. joined_domains = {} # type: Dict[str, int]
  879. for u, d in joined_users:
  880. try:
  881. dom = get_domain_from_id(u)
  882. old_d = joined_domains.get(dom)
  883. if old_d:
  884. joined_domains[dom] = min(d, old_d)
  885. else:
  886. joined_domains[dom] = d
  887. except Exception:
  888. pass
  889. return sorted(joined_domains.items(), key=lambda d: d[1])
  890. curr_domains = get_domains_from_state(curr_state)
  891. likely_domains = [
  892. domain for domain, depth in curr_domains if domain != self.server_name
  893. ]
  894. async def try_backfill(domains):
  895. # TODO: Should we try multiple of these at a time?
  896. for dom in domains:
  897. try:
  898. await self.backfill(
  899. dom, room_id, limit=100, extremities=extremities
  900. )
  901. # If this succeeded then we probably already have the
  902. # appropriate stuff.
  903. # TODO: We can probably do something more intelligent here.
  904. return True
  905. except SynapseError as e:
  906. logger.info("Failed to backfill from %s because %s", dom, e)
  907. continue
  908. except HttpResponseException as e:
  909. if 400 <= e.code < 500:
  910. raise e.to_synapse_error()
  911. logger.info("Failed to backfill from %s because %s", dom, e)
  912. continue
  913. except CodeMessageException as e:
  914. if 400 <= e.code < 500:
  915. raise
  916. logger.info("Failed to backfill from %s because %s", dom, e)
  917. continue
  918. except NotRetryingDestination as e:
  919. logger.info(str(e))
  920. continue
  921. except RequestSendFailed as e:
  922. logger.info("Falied to get backfill from %s because %s", dom, e)
  923. continue
  924. except FederationDeniedError as e:
  925. logger.info(e)
  926. continue
  927. except Exception as e:
  928. logger.exception("Failed to backfill from %s because %s", dom, e)
  929. continue
  930. return False
  931. success = await try_backfill(likely_domains)
  932. if success:
  933. return True
  934. # Huh, well *those* domains didn't work out. Lets try some domains
  935. # from the time.
  936. tried_domains = set(likely_domains)
  937. tried_domains.add(self.server_name)
  938. event_ids = list(extremities.keys())
  939. logger.debug("calling resolve_state_groups in _maybe_backfill")
  940. resolve = preserve_fn(self.state_handler.resolve_state_groups_for_events)
  941. states = await make_deferred_yieldable(
  942. defer.gatherResults(
  943. [resolve(room_id, [e]) for e in event_ids], consumeErrors=True
  944. )
  945. )
  946. # dict[str, dict[tuple, str]], a map from event_id to state map of
  947. # event_ids.
  948. states = dict(zip(event_ids, [s.state for s in states]))
  949. state_map = await self.store.get_events(
  950. [e_id for ids in states.values() for e_id in ids.values()],
  951. get_prev_content=False,
  952. )
  953. states = {
  954. key: {
  955. k: state_map[e_id]
  956. for k, e_id in state_dict.items()
  957. if e_id in state_map
  958. }
  959. for key, state_dict in states.items()
  960. }
  961. for e_id, _ in sorted_extremeties_tuple:
  962. likely_domains = get_domains_from_state(states[e_id])
  963. success = await try_backfill(
  964. [dom for dom, _ in likely_domains if dom not in tried_domains]
  965. )
  966. if success:
  967. return True
  968. tried_domains.update(dom for dom, _ in likely_domains)
  969. return False
  970. async def _get_events_and_persist(
  971. self, destination: str, room_id: str, events: Iterable[str]
  972. ):
  973. """Fetch the given events from a server, and persist them as outliers.
  974. This function *does not* recursively get missing auth events of the
  975. newly fetched events. Callers must include in the `events` argument
  976. any missing events from the auth chain.
  977. Logs a warning if we can't find the given event.
  978. """
  979. room_version = await self.store.get_room_version(room_id)
  980. event_map = {} # type: Dict[str, EventBase]
  981. async def get_event(event_id: str):
  982. with nested_logging_context(event_id):
  983. try:
  984. event = await self.federation_client.get_pdu(
  985. [destination], event_id, room_version, outlier=True,
  986. )
  987. if event is None:
  988. logger.warning(
  989. "Server %s didn't return event %s", destination, event_id,
  990. )
  991. return
  992. event_map[event.event_id] = event
  993. except Exception as e:
  994. logger.warning(
  995. "Error fetching missing state/auth event %s: %s %s",
  996. event_id,
  997. type(e),
  998. e,
  999. )
  1000. await concurrently_execute(get_event, events, 5)
  1001. # Make a map of auth events for each event. We do this after fetching
  1002. # all the events as some of the events' auth events will be in the list
  1003. # of requested events.
  1004. auth_events = [
  1005. aid
  1006. for event in event_map.values()
  1007. for aid in event.auth_event_ids()
  1008. if aid not in event_map
  1009. ]
  1010. persisted_events = await self.store.get_events(
  1011. auth_events, allow_rejected=True,
  1012. )
  1013. event_infos = []
  1014. for event in event_map.values():
  1015. auth = {}
  1016. for auth_event_id in event.auth_event_ids():
  1017. ae = persisted_events.get(auth_event_id) or event_map.get(auth_event_id)
  1018. if ae:
  1019. auth[(ae.type, ae.state_key)] = ae
  1020. else:
  1021. logger.info("Missing auth event %s", auth_event_id)
  1022. event_infos.append(_NewEventInfo(event, None, auth))
  1023. await self._handle_new_events(
  1024. destination, event_infos,
  1025. )
  1026. def _sanity_check_event(self, ev):
  1027. """
  1028. Do some early sanity checks of a received event
  1029. In particular, checks it doesn't have an excessive number of
  1030. prev_events or auth_events, which could cause a huge state resolution
  1031. or cascade of event fetches.
  1032. Args:
  1033. ev (synapse.events.EventBase): event to be checked
  1034. Returns: None
  1035. Raises:
  1036. SynapseError if the event does not pass muster
  1037. """
  1038. if len(ev.prev_event_ids()) > 20:
  1039. logger.warning(
  1040. "Rejecting event %s which has %i prev_events",
  1041. ev.event_id,
  1042. len(ev.prev_event_ids()),
  1043. )
  1044. raise SynapseError(HTTPStatus.BAD_REQUEST, "Too many prev_events")
  1045. if len(ev.auth_event_ids()) > 10:
  1046. logger.warning(
  1047. "Rejecting event %s which has %i auth_events",
  1048. ev.event_id,
  1049. len(ev.auth_event_ids()),
  1050. )
  1051. raise SynapseError(HTTPStatus.BAD_REQUEST, "Too many auth_events")
  1052. async def send_invite(self, target_host, event):
  1053. """ Sends the invite to the remote server for signing.
  1054. Invites must be signed by the invitee's server before distribution.
  1055. """
  1056. pdu = await self.federation_client.send_invite(
  1057. destination=target_host,
  1058. room_id=event.room_id,
  1059. event_id=event.event_id,
  1060. pdu=event,
  1061. )
  1062. return pdu
  1063. async def on_event_auth(self, event_id: str) -> List[EventBase]:
  1064. event = await self.store.get_event(event_id)
  1065. auth = await self.store.get_auth_chain(
  1066. list(event.auth_event_ids()), include_given=True
  1067. )
  1068. return list(auth)
  1069. async def do_invite_join(
  1070. self, target_hosts: Iterable[str], room_id: str, joinee: str, content: JsonDict
  1071. ) -> Tuple[str, int]:
  1072. """ Attempts to join the `joinee` to the room `room_id` via the
  1073. servers contained in `target_hosts`.
  1074. This first triggers a /make_join/ request that returns a partial
  1075. event that we can fill out and sign. This is then sent to the
  1076. remote server via /send_join/ which responds with the state at that
  1077. event and the auth_chains.
  1078. We suspend processing of any received events from this room until we
  1079. have finished processing the join.
  1080. Args:
  1081. target_hosts: List of servers to attempt to join the room with.
  1082. room_id: The ID of the room to join.
  1083. joinee: The User ID of the joining user.
  1084. content: The event content to use for the join event.
  1085. """
  1086. # TODO: We should be able to call this on workers, but the upgrading of
  1087. # room stuff after join currently doesn't work on workers.
  1088. assert self.config.worker.worker_app is None
  1089. logger.debug("Joining %s to %s", joinee, room_id)
  1090. origin, event, room_version_obj = await self._make_and_verify_event(
  1091. target_hosts,
  1092. room_id,
  1093. joinee,
  1094. "join",
  1095. content,
  1096. params={"ver": KNOWN_ROOM_VERSIONS},
  1097. )
  1098. # This shouldn't happen, because the RoomMemberHandler has a
  1099. # linearizer lock which only allows one operation per user per room
  1100. # at a time - so this is just paranoia.
  1101. assert room_id not in self.room_queues
  1102. self.room_queues[room_id] = []
  1103. await self._clean_room_for_join(room_id)
  1104. handled_events = set()
  1105. try:
  1106. # Try the host we successfully got a response to /make_join/
  1107. # request first.
  1108. host_list = list(target_hosts)
  1109. try:
  1110. host_list.remove(origin)
  1111. host_list.insert(0, origin)
  1112. except ValueError:
  1113. pass
  1114. ret = await self.federation_client.send_join(
  1115. host_list, event, room_version_obj
  1116. )
  1117. origin = ret["origin"]
  1118. state = ret["state"]
  1119. auth_chain = ret["auth_chain"]
  1120. auth_chain.sort(key=lambda e: e.depth)
  1121. handled_events.update([s.event_id for s in state])
  1122. handled_events.update([a.event_id for a in auth_chain])
  1123. handled_events.add(event.event_id)
  1124. logger.debug("do_invite_join auth_chain: %s", auth_chain)
  1125. logger.debug("do_invite_join state: %s", state)
  1126. logger.debug("do_invite_join event: %s", event)
  1127. # if this is the first time we've joined this room, it's time to add
  1128. # a row to `rooms` with the correct room version. If there's already a
  1129. # row there, we should override it, since it may have been populated
  1130. # based on an invite request which lied about the room version.
  1131. #
  1132. # federation_client.send_join has already checked that the room
  1133. # version in the received create event is the same as room_version_obj,
  1134. # so we can rely on it now.
  1135. #
  1136. await self.store.upsert_room_on_join(
  1137. room_id=room_id, room_version=room_version_obj,
  1138. )
  1139. max_stream_id = await self._persist_auth_tree(
  1140. origin, auth_chain, state, event, room_version_obj
  1141. )
  1142. # We wait here until this instance has seen the events come down
  1143. # replication (if we're using replication) as the below uses caches.
  1144. #
  1145. # TODO: Currently the events stream is written to from master
  1146. await self._replication.wait_for_stream_position(
  1147. self.config.worker.writers.events, "events", max_stream_id
  1148. )
  1149. # Check whether this room is the result of an upgrade of a room we already know
  1150. # about. If so, migrate over user information
  1151. predecessor = await self.store.get_room_predecessor(room_id)
  1152. if not predecessor or not isinstance(predecessor.get("room_id"), str):
  1153. return event.event_id, max_stream_id
  1154. old_room_id = predecessor["room_id"]
  1155. logger.debug(
  1156. "Found predecessor for %s during remote join: %s", room_id, old_room_id
  1157. )
  1158. # We retrieve the room member handler here as to not cause a cyclic dependency
  1159. member_handler = self.hs.get_room_member_handler()
  1160. await member_handler.transfer_room_state_on_room_upgrade(
  1161. old_room_id, room_id
  1162. )
  1163. logger.debug("Finished joining %s to %s", joinee, room_id)
  1164. return event.event_id, max_stream_id
  1165. finally:
  1166. room_queue = self.room_queues[room_id]
  1167. del self.room_queues[room_id]
  1168. # we don't need to wait for the queued events to be processed -
  1169. # it's just a best-effort thing at this point. We do want to do
  1170. # them roughly in order, though, otherwise we'll end up making
  1171. # lots of requests for missing prev_events which we do actually
  1172. # have. Hence we fire off the background task, but don't wait for it.
  1173. run_in_background(self._handle_queued_pdus, room_queue)
  1174. async def _handle_queued_pdus(self, room_queue):
  1175. """Process PDUs which got queued up while we were busy send_joining.
  1176. Args:
  1177. room_queue (list[FrozenEvent, str]): list of PDUs to be processed
  1178. and the servers that sent them
  1179. """
  1180. for p, origin in room_queue:
  1181. try:
  1182. logger.info(
  1183. "Processing queued PDU %s which was received "
  1184. "while we were joining %s",
  1185. p.event_id,
  1186. p.room_id,
  1187. )
  1188. with nested_logging_context(p.event_id):
  1189. await self.on_receive_pdu(origin, p, sent_to_us_directly=True)
  1190. except Exception as e:
  1191. logger.warning(
  1192. "Error handling queued PDU %s from %s: %s", p.event_id, origin, e
  1193. )
  1194. async def on_make_join_request(
  1195. self, origin: str, room_id: str, user_id: str
  1196. ) -> EventBase:
  1197. """ We've received a /make_join/ request, so we create a partial
  1198. join event for the room and return that. We do *not* persist or
  1199. process it until the other server has signed it and sent it back.
  1200. Args:
  1201. origin: The (verified) server name of the requesting server.
  1202. room_id: Room to create join event in
  1203. user_id: The user to create the join for
  1204. """
  1205. if get_domain_from_id(user_id) != origin:
  1206. logger.info(
  1207. "Got /make_join request for user %r from different origin %s, ignoring",
  1208. user_id,
  1209. origin,
  1210. )
  1211. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  1212. # checking the room version will check that we've actually heard of the room
  1213. # (and return a 404 otherwise)
  1214. room_version = await self.store.get_room_version_id(room_id)
  1215. # now check that we are *still* in the room
  1216. is_in_room = await self.auth.check_host_in_room(room_id, self.server_name)
  1217. if not is_in_room:
  1218. logger.info(
  1219. "Got /make_join request for room %s we are no longer in", room_id,
  1220. )
  1221. raise NotFoundError("Not an active room on this server")
  1222. event_content = {"membership": Membership.JOIN}
  1223. builder = self.event_builder_factory.new(
  1224. room_version,
  1225. {
  1226. "type": EventTypes.Member,
  1227. "content": event_content,
  1228. "room_id": room_id,
  1229. "sender": user_id,
  1230. "state_key": user_id,
  1231. },
  1232. )
  1233. try:
  1234. event, context = await self.event_creation_handler.create_new_client_event(
  1235. builder=builder
  1236. )
  1237. except AuthError as e:
  1238. logger.warning("Failed to create join to %s because %s", room_id, e)
  1239. raise e
  1240. event_allowed = await self.third_party_event_rules.check_event_allowed(
  1241. event, context
  1242. )
  1243. if not event_allowed:
  1244. logger.info("Creation of join %s forbidden by third-party rules", event)
  1245. raise SynapseError(
  1246. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  1247. )
  1248. # The remote hasn't signed it yet, obviously. We'll do the full checks
  1249. # when we get the event back in `on_send_join_request`
  1250. await self.auth.check_from_context(
  1251. room_version, event, context, do_sig_check=False
  1252. )
  1253. return event
  1254. async def on_send_join_request(self, origin, pdu):
  1255. """ We have received a join event for a room. Fully process it and
  1256. respond with the current state and auth chains.
  1257. """
  1258. event = pdu
  1259. logger.debug(
  1260. "on_send_join_request from %s: Got event: %s, signatures: %s",
  1261. origin,
  1262. event.event_id,
  1263. event.signatures,
  1264. )
  1265. if get_domain_from_id(event.sender) != origin:
  1266. logger.info(
  1267. "Got /send_join request for user %r from different origin %s",
  1268. event.sender,
  1269. origin,
  1270. )
  1271. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  1272. event.internal_metadata.outlier = False
  1273. # Send this event on behalf of the origin server.
  1274. #
  1275. # The reasons we have the destination server rather than the origin
  1276. # server send it are slightly mysterious: the origin server should have
  1277. # all the neccessary state once it gets the response to the send_join,
  1278. # so it could send the event itself if it wanted to. It may be that
  1279. # doing it this way reduces failure modes, or avoids certain attacks
  1280. # where a new server selectively tells a subset of the federation that
  1281. # it has joined.
  1282. #
  1283. # The fact is that, as of the current writing, Synapse doesn't send out
  1284. # the join event over federation after joining, and changing it now
  1285. # would introduce the danger of backwards-compatibility problems.
  1286. event.internal_metadata.send_on_behalf_of = origin
  1287. context = await self._handle_new_event(origin, event)
  1288. event_allowed = await self.third_party_event_rules.check_event_allowed(
  1289. event, context
  1290. )
  1291. if not event_allowed:
  1292. logger.info("Sending of join %s forbidden by third-party rules", event)
  1293. raise SynapseError(
  1294. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  1295. )
  1296. logger.debug(
  1297. "on_send_join_request: After _handle_new_event: %s, sigs: %s",
  1298. event.event_id,
  1299. event.signatures,
  1300. )
  1301. if event.type == EventTypes.Member:
  1302. if event.content["membership"] == Membership.JOIN:
  1303. user = UserID.from_string(event.state_key)
  1304. await self.user_joined_room(user, event.room_id)
  1305. prev_state_ids = await context.get_prev_state_ids()
  1306. state_ids = list(prev_state_ids.values())
  1307. auth_chain = await self.store.get_auth_chain(state_ids)
  1308. state = await self.store.get_events(list(prev_state_ids.values()))
  1309. return {"state": list(state.values()), "auth_chain": auth_chain}
  1310. async def on_invite_request(
  1311. self, origin: str, event: EventBase, room_version: RoomVersion
  1312. ):
  1313. """ We've got an invite event. Process and persist it. Sign it.
  1314. Respond with the now signed event.
  1315. """
  1316. if event.state_key is None:
  1317. raise SynapseError(400, "The invite event did not have a state key")
  1318. is_blocked = await self.store.is_room_blocked(event.room_id)
  1319. if is_blocked:
  1320. raise SynapseError(403, "This room has been blocked on this server")
  1321. if self.hs.config.block_non_admin_invites:
  1322. raise SynapseError(403, "This server does not accept room invites")
  1323. if not self.spam_checker.user_may_invite(
  1324. event.sender, event.state_key, event.room_id
  1325. ):
  1326. raise SynapseError(
  1327. 403, "This user is not permitted to send invites to this server/user"
  1328. )
  1329. membership = event.content.get("membership")
  1330. if event.type != EventTypes.Member or membership != Membership.INVITE:
  1331. raise SynapseError(400, "The event was not an m.room.member invite event")
  1332. sender_domain = get_domain_from_id(event.sender)
  1333. if sender_domain != origin:
  1334. raise SynapseError(
  1335. 400, "The invite event was not from the server sending it"
  1336. )
  1337. if not self.is_mine_id(event.state_key):
  1338. raise SynapseError(400, "The invite event must be for this server")
  1339. # block any attempts to invite the server notices mxid
  1340. if event.state_key == self._server_notices_mxid:
  1341. raise SynapseError(HTTPStatus.FORBIDDEN, "Cannot invite this user")
  1342. # keep a record of the room version, if we don't yet know it.
  1343. # (this may get overwritten if we later get a different room version in a
  1344. # join dance).
  1345. await self._maybe_store_room_on_invite(
  1346. room_id=event.room_id, room_version=room_version
  1347. )
  1348. event.internal_metadata.outlier = True
  1349. event.internal_metadata.out_of_band_membership = True
  1350. event.signatures.update(
  1351. compute_event_signature(
  1352. room_version,
  1353. event.get_pdu_json(),
  1354. self.hs.hostname,
  1355. self.hs.signing_key,
  1356. )
  1357. )
  1358. context = await self.state_handler.compute_event_context(event)
  1359. await self.persist_events_and_notify([(event, context)])
  1360. return event
  1361. async def do_remotely_reject_invite(
  1362. self, target_hosts: Iterable[str], room_id: str, user_id: str, content: JsonDict
  1363. ) -> Tuple[EventBase, int]:
  1364. origin, event, room_version = await self._make_and_verify_event(
  1365. target_hosts, room_id, user_id, "leave", content=content
  1366. )
  1367. # Mark as outlier as we don't have any state for this event; we're not
  1368. # even in the room.
  1369. event.internal_metadata.outlier = True
  1370. event.internal_metadata.out_of_band_membership = True
  1371. # Try the host that we succesfully called /make_leave/ on first for
  1372. # the /send_leave/ request.
  1373. host_list = list(target_hosts)
  1374. try:
  1375. host_list.remove(origin)
  1376. host_list.insert(0, origin)
  1377. except ValueError:
  1378. pass
  1379. await self.federation_client.send_leave(host_list, event)
  1380. context = await self.state_handler.compute_event_context(event)
  1381. stream_id = await self.persist_events_and_notify([(event, context)])
  1382. return event, stream_id
  1383. async def _make_and_verify_event(
  1384. self,
  1385. target_hosts: Iterable[str],
  1386. room_id: str,
  1387. user_id: str,
  1388. membership: str,
  1389. content: JsonDict = {},
  1390. params: Optional[Dict[str, Union[str, Iterable[str]]]] = None,
  1391. ) -> Tuple[str, EventBase, RoomVersion]:
  1392. (
  1393. origin,
  1394. event,
  1395. room_version,
  1396. ) = await self.federation_client.make_membership_event(
  1397. target_hosts, room_id, user_id, membership, content, params=params
  1398. )
  1399. logger.debug("Got response to make_%s: %s", membership, event)
  1400. # We should assert some things.
  1401. # FIXME: Do this in a nicer way
  1402. assert event.type == EventTypes.Member
  1403. assert event.user_id == user_id
  1404. assert event.state_key == user_id
  1405. assert event.room_id == room_id
  1406. return origin, event, room_version
  1407. async def on_make_leave_request(
  1408. self, origin: str, room_id: str, user_id: str
  1409. ) -> EventBase:
  1410. """ We've received a /make_leave/ request, so we create a partial
  1411. leave event for the room and return that. We do *not* persist or
  1412. process it until the other server has signed it and sent it back.
  1413. Args:
  1414. origin: The (verified) server name of the requesting server.
  1415. room_id: Room to create leave event in
  1416. user_id: The user to create the leave for
  1417. """
  1418. if get_domain_from_id(user_id) != origin:
  1419. logger.info(
  1420. "Got /make_leave request for user %r from different origin %s, ignoring",
  1421. user_id,
  1422. origin,
  1423. )
  1424. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  1425. room_version = await self.store.get_room_version_id(room_id)
  1426. builder = self.event_builder_factory.new(
  1427. room_version,
  1428. {
  1429. "type": EventTypes.Member,
  1430. "content": {"membership": Membership.LEAVE},
  1431. "room_id": room_id,
  1432. "sender": user_id,
  1433. "state_key": user_id,
  1434. },
  1435. )
  1436. event, context = await self.event_creation_handler.create_new_client_event(
  1437. builder=builder
  1438. )
  1439. event_allowed = await self.third_party_event_rules.check_event_allowed(
  1440. event, context
  1441. )
  1442. if not event_allowed:
  1443. logger.warning("Creation of leave %s forbidden by third-party rules", event)
  1444. raise SynapseError(
  1445. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  1446. )
  1447. try:
  1448. # The remote hasn't signed it yet, obviously. We'll do the full checks
  1449. # when we get the event back in `on_send_leave_request`
  1450. await self.auth.check_from_context(
  1451. room_version, event, context, do_sig_check=False
  1452. )
  1453. except AuthError as e:
  1454. logger.warning("Failed to create new leave %r because %s", event, e)
  1455. raise e
  1456. return event
  1457. async def on_send_leave_request(self, origin, pdu):
  1458. """ We have received a leave event for a room. Fully process it."""
  1459. event = pdu
  1460. logger.debug(
  1461. "on_send_leave_request: Got event: %s, signatures: %s",
  1462. event.event_id,
  1463. event.signatures,
  1464. )
  1465. if get_domain_from_id(event.sender) != origin:
  1466. logger.info(
  1467. "Got /send_leave request for user %r from different origin %s",
  1468. event.sender,
  1469. origin,
  1470. )
  1471. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  1472. event.internal_metadata.outlier = False
  1473. context = await self._handle_new_event(origin, event)
  1474. event_allowed = await self.third_party_event_rules.check_event_allowed(
  1475. event, context
  1476. )
  1477. if not event_allowed:
  1478. logger.info("Sending of leave %s forbidden by third-party rules", event)
  1479. raise SynapseError(
  1480. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  1481. )
  1482. logger.debug(
  1483. "on_send_leave_request: After _handle_new_event: %s, sigs: %s",
  1484. event.event_id,
  1485. event.signatures,
  1486. )
  1487. return None
  1488. async def get_state_for_pdu(self, room_id: str, event_id: str) -> List[EventBase]:
  1489. """Returns the state at the event. i.e. not including said event.
  1490. """
  1491. event = await self.store.get_event(
  1492. event_id, allow_none=False, check_room_id=room_id
  1493. )
  1494. state_groups = await self.state_store.get_state_groups(room_id, [event_id])
  1495. if state_groups:
  1496. _, state = list(state_groups.items()).pop()
  1497. results = {(e.type, e.state_key): e for e in state}
  1498. if event.is_state():
  1499. # Get previous state
  1500. if "replaces_state" in event.unsigned:
  1501. prev_id = event.unsigned["replaces_state"]
  1502. if prev_id != event.event_id:
  1503. prev_event = await self.store.get_event(prev_id)
  1504. results[(event.type, event.state_key)] = prev_event
  1505. else:
  1506. del results[(event.type, event.state_key)]
  1507. res = list(results.values())
  1508. return res
  1509. else:
  1510. return []
  1511. async def get_state_ids_for_pdu(self, room_id: str, event_id: str) -> List[str]:
  1512. """Returns the state at the event. i.e. not including said event.
  1513. """
  1514. event = await self.store.get_event(
  1515. event_id, allow_none=False, check_room_id=room_id
  1516. )
  1517. state_groups = await self.state_store.get_state_groups_ids(room_id, [event_id])
  1518. if state_groups:
  1519. _, state = list(state_groups.items()).pop()
  1520. results = state
  1521. if event.is_state():
  1522. # Get previous state
  1523. if "replaces_state" in event.unsigned:
  1524. prev_id = event.unsigned["replaces_state"]
  1525. if prev_id != event.event_id:
  1526. results[(event.type, event.state_key)] = prev_id
  1527. else:
  1528. results.pop((event.type, event.state_key), None)
  1529. return list(results.values())
  1530. else:
  1531. return []
  1532. @log_function
  1533. async def on_backfill_request(
  1534. self, origin: str, room_id: str, pdu_list: List[str], limit: int
  1535. ) -> List[EventBase]:
  1536. in_room = await self.auth.check_host_in_room(room_id, origin)
  1537. if not in_room:
  1538. raise AuthError(403, "Host not in room.")
  1539. # Synapse asks for 100 events per backfill request. Do not allow more.
  1540. limit = min(limit, 100)
  1541. events = await self.store.get_backfill_events(room_id, pdu_list, limit)
  1542. events = await filter_events_for_server(self.storage, origin, events)
  1543. return events
  1544. @log_function
  1545. async def get_persisted_pdu(
  1546. self, origin: str, event_id: str
  1547. ) -> Optional[EventBase]:
  1548. """Get an event from the database for the given server.
  1549. Args:
  1550. origin: hostname of server which is requesting the event; we
  1551. will check that the server is allowed to see it.
  1552. event_id: id of the event being requested
  1553. Returns:
  1554. None if we know nothing about the event; otherwise the (possibly-redacted) event.
  1555. Raises:
  1556. AuthError if the server is not currently in the room
  1557. """
  1558. event = await self.store.get_event(
  1559. event_id, allow_none=True, allow_rejected=True
  1560. )
  1561. if event:
  1562. in_room = await self.auth.check_host_in_room(event.room_id, origin)
  1563. if not in_room:
  1564. raise AuthError(403, "Host not in room.")
  1565. events = await filter_events_for_server(self.storage, origin, [event])
  1566. event = events[0]
  1567. return event
  1568. else:
  1569. return None
  1570. def get_min_depth_for_context(self, context):
  1571. return self.store.get_min_depth(context)
  1572. async def _handle_new_event(
  1573. self, origin, event, state=None, auth_events=None, backfilled=False
  1574. ):
  1575. context = await self._prep_event(
  1576. origin, event, state=state, auth_events=auth_events, backfilled=backfilled
  1577. )
  1578. try:
  1579. if (
  1580. not event.internal_metadata.is_outlier()
  1581. and not backfilled
  1582. and not context.rejected
  1583. ):
  1584. await self.action_generator.handle_push_actions_for_event(
  1585. event, context
  1586. )
  1587. await self.persist_events_and_notify(
  1588. [(event, context)], backfilled=backfilled
  1589. )
  1590. except Exception:
  1591. run_in_background(
  1592. self.store.remove_push_actions_from_staging, event.event_id
  1593. )
  1594. raise
  1595. return context
  1596. async def _handle_new_events(
  1597. self,
  1598. origin: str,
  1599. event_infos: Iterable[_NewEventInfo],
  1600. backfilled: bool = False,
  1601. ) -> None:
  1602. """Creates the appropriate contexts and persists events. The events
  1603. should not depend on one another, e.g. this should be used to persist
  1604. a bunch of outliers, but not a chunk of individual events that depend
  1605. on each other for state calculations.
  1606. Notifies about the events where appropriate.
  1607. """
  1608. async def prep(ev_info: _NewEventInfo):
  1609. event = ev_info.event
  1610. with nested_logging_context(suffix=event.event_id):
  1611. res = await self._prep_event(
  1612. origin,
  1613. event,
  1614. state=ev_info.state,
  1615. auth_events=ev_info.auth_events,
  1616. backfilled=backfilled,
  1617. )
  1618. return res
  1619. contexts = await make_deferred_yieldable(
  1620. defer.gatherResults(
  1621. [run_in_background(prep, ev_info) for ev_info in event_infos],
  1622. consumeErrors=True,
  1623. )
  1624. )
  1625. await self.persist_events_and_notify(
  1626. [
  1627. (ev_info.event, context)
  1628. for ev_info, context in zip(event_infos, contexts)
  1629. ],
  1630. backfilled=backfilled,
  1631. )
  1632. async def _persist_auth_tree(
  1633. self,
  1634. origin: str,
  1635. auth_events: List[EventBase],
  1636. state: List[EventBase],
  1637. event: EventBase,
  1638. room_version: RoomVersion,
  1639. ) -> int:
  1640. """Checks the auth chain is valid (and passes auth checks) for the
  1641. state and event. Then persists the auth chain and state atomically.
  1642. Persists the event separately. Notifies about the persisted events
  1643. where appropriate.
  1644. Will attempt to fetch missing auth events.
  1645. Args:
  1646. origin: Where the events came from
  1647. auth_events
  1648. state
  1649. event
  1650. room_version: The room version we expect this room to have, and
  1651. will raise if it doesn't match the version in the create event.
  1652. """
  1653. events_to_context = {}
  1654. for e in itertools.chain(auth_events, state):
  1655. e.internal_metadata.outlier = True
  1656. ctx = await self.state_handler.compute_event_context(e)
  1657. events_to_context[e.event_id] = ctx
  1658. event_map = {
  1659. e.event_id: e for e in itertools.chain(auth_events, state, [event])
  1660. }
  1661. create_event = None
  1662. for e in auth_events:
  1663. if (e.type, e.state_key) == (EventTypes.Create, ""):
  1664. create_event = e
  1665. break
  1666. if create_event is None:
  1667. # If the state doesn't have a create event then the room is
  1668. # invalid, and it would fail auth checks anyway.
  1669. raise SynapseError(400, "No create event in state")
  1670. room_version_id = create_event.content.get(
  1671. "room_version", RoomVersions.V1.identifier
  1672. )
  1673. if room_version.identifier != room_version_id:
  1674. raise SynapseError(400, "Room version mismatch")
  1675. missing_auth_events = set()
  1676. for e in itertools.chain(auth_events, state, [event]):
  1677. for e_id in e.auth_event_ids():
  1678. if e_id not in event_map:
  1679. missing_auth_events.add(e_id)
  1680. for e_id in missing_auth_events:
  1681. m_ev = await self.federation_client.get_pdu(
  1682. [origin], e_id, room_version=room_version, outlier=True, timeout=10000,
  1683. )
  1684. if m_ev and m_ev.event_id == e_id:
  1685. event_map[e_id] = m_ev
  1686. else:
  1687. logger.info("Failed to find auth event %r", e_id)
  1688. for e in itertools.chain(auth_events, state, [event]):
  1689. auth_for_e = {
  1690. (event_map[e_id].type, event_map[e_id].state_key): event_map[e_id]
  1691. for e_id in e.auth_event_ids()
  1692. if e_id in event_map
  1693. }
  1694. if create_event:
  1695. auth_for_e[(EventTypes.Create, "")] = create_event
  1696. try:
  1697. event_auth.check(room_version, e, auth_events=auth_for_e)
  1698. except SynapseError as err:
  1699. # we may get SynapseErrors here as well as AuthErrors. For
  1700. # instance, there are a couple of (ancient) events in some
  1701. # rooms whose senders do not have the correct sigil; these
  1702. # cause SynapseErrors in auth.check. We don't want to give up
  1703. # the attempt to federate altogether in such cases.
  1704. logger.warning("Rejecting %s because %s", e.event_id, err.msg)
  1705. if e == event:
  1706. raise
  1707. events_to_context[e.event_id].rejected = RejectedReason.AUTH_ERROR
  1708. await self.persist_events_and_notify(
  1709. [
  1710. (e, events_to_context[e.event_id])
  1711. for e in itertools.chain(auth_events, state)
  1712. ]
  1713. )
  1714. new_event_context = await self.state_handler.compute_event_context(
  1715. event, old_state=state
  1716. )
  1717. return await self.persist_events_and_notify([(event, new_event_context)])
  1718. async def _prep_event(
  1719. self,
  1720. origin: str,
  1721. event: EventBase,
  1722. state: Optional[Iterable[EventBase]],
  1723. auth_events: Optional[StateMap[EventBase]],
  1724. backfilled: bool,
  1725. ) -> EventContext:
  1726. context = await self.state_handler.compute_event_context(event, old_state=state)
  1727. if not auth_events:
  1728. prev_state_ids = await context.get_prev_state_ids()
  1729. auth_events_ids = await self.auth.compute_auth_events(
  1730. event, prev_state_ids, for_verification=True
  1731. )
  1732. auth_events_x = await self.store.get_events(auth_events_ids)
  1733. auth_events = {(e.type, e.state_key): e for e in auth_events_x.values()}
  1734. # This is a hack to fix some old rooms where the initial join event
  1735. # didn't reference the create event in its auth events.
  1736. if event.type == EventTypes.Member and not event.auth_event_ids():
  1737. if len(event.prev_event_ids()) == 1 and event.depth < 5:
  1738. c = await self.store.get_event(
  1739. event.prev_event_ids()[0], allow_none=True
  1740. )
  1741. if c and c.type == EventTypes.Create:
  1742. auth_events[(c.type, c.state_key)] = c
  1743. context = await self.do_auth(origin, event, context, auth_events=auth_events)
  1744. if not context.rejected:
  1745. await self._check_for_soft_fail(event, state, backfilled)
  1746. if event.type == EventTypes.GuestAccess and not context.rejected:
  1747. await self.maybe_kick_guest_users(event)
  1748. return context
  1749. async def _check_for_soft_fail(
  1750. self, event: EventBase, state: Optional[Iterable[EventBase]], backfilled: bool
  1751. ) -> None:
  1752. """Checks if we should soft fail the event; if so, marks the event as
  1753. such.
  1754. Args:
  1755. event
  1756. state: The state at the event if we don't have all the event's prev events
  1757. backfilled: Whether the event is from backfill
  1758. """
  1759. # For new (non-backfilled and non-outlier) events we check if the event
  1760. # passes auth based on the current state. If it doesn't then we
  1761. # "soft-fail" the event.
  1762. if backfilled or event.internal_metadata.is_outlier():
  1763. return
  1764. extrem_ids = await self.store.get_latest_event_ids_in_room(event.room_id)
  1765. extrem_ids = set(extrem_ids)
  1766. prev_event_ids = set(event.prev_event_ids())
  1767. if extrem_ids == prev_event_ids:
  1768. # If they're the same then the current state is the same as the
  1769. # state at the event, so no point rechecking auth for soft fail.
  1770. return
  1771. room_version = await self.store.get_room_version_id(event.room_id)
  1772. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1773. # Calculate the "current state".
  1774. if state is not None:
  1775. # If we're explicitly given the state then we won't have all the
  1776. # prev events, and so we have a gap in the graph. In this case
  1777. # we want to be a little careful as we might have been down for
  1778. # a while and have an incorrect view of the current state,
  1779. # however we still want to do checks as gaps are easy to
  1780. # maliciously manufacture.
  1781. #
  1782. # So we use a "current state" that is actually a state
  1783. # resolution across the current forward extremities and the
  1784. # given state at the event. This should correctly handle cases
  1785. # like bans, especially with state res v2.
  1786. state_sets = await self.state_store.get_state_groups(
  1787. event.room_id, extrem_ids
  1788. )
  1789. state_sets = list(state_sets.values())
  1790. state_sets.append(state)
  1791. current_state_ids = await self.state_handler.resolve_events(
  1792. room_version, state_sets, event
  1793. )
  1794. current_state_ids = {k: e.event_id for k, e in current_state_ids.items()}
  1795. else:
  1796. current_state_ids = await self.state_handler.get_current_state_ids(
  1797. event.room_id, latest_event_ids=extrem_ids
  1798. )
  1799. logger.debug(
  1800. "Doing soft-fail check for %s: state %s", event.event_id, current_state_ids,
  1801. )
  1802. # Now check if event pass auth against said current state
  1803. auth_types = auth_types_for_event(event)
  1804. current_state_ids = [e for k, e in current_state_ids.items() if k in auth_types]
  1805. current_auth_events = await self.store.get_events(current_state_ids)
  1806. current_auth_events = {
  1807. (e.type, e.state_key): e for e in current_auth_events.values()
  1808. }
  1809. try:
  1810. event_auth.check(room_version_obj, event, auth_events=current_auth_events)
  1811. except AuthError as e:
  1812. logger.warning("Soft-failing %r because %s", event, e)
  1813. event.internal_metadata.soft_failed = True
  1814. async def on_query_auth(
  1815. self, origin, event_id, room_id, remote_auth_chain, rejects, missing
  1816. ):
  1817. in_room = await self.auth.check_host_in_room(room_id, origin)
  1818. if not in_room:
  1819. raise AuthError(403, "Host not in room.")
  1820. event = await self.store.get_event(
  1821. event_id, allow_none=False, check_room_id=room_id
  1822. )
  1823. # Just go through and process each event in `remote_auth_chain`. We
  1824. # don't want to fall into the trap of `missing` being wrong.
  1825. for e in remote_auth_chain:
  1826. try:
  1827. await self._handle_new_event(origin, e)
  1828. except AuthError:
  1829. pass
  1830. # Now get the current auth_chain for the event.
  1831. local_auth_chain = await self.store.get_auth_chain(
  1832. list(event.auth_event_ids()), include_given=True
  1833. )
  1834. # TODO: Check if we would now reject event_id. If so we need to tell
  1835. # everyone.
  1836. ret = await self.construct_auth_difference(local_auth_chain, remote_auth_chain)
  1837. logger.debug("on_query_auth returning: %s", ret)
  1838. return ret
  1839. async def on_get_missing_events(
  1840. self, origin, room_id, earliest_events, latest_events, limit
  1841. ):
  1842. in_room = await self.auth.check_host_in_room(room_id, origin)
  1843. if not in_room:
  1844. raise AuthError(403, "Host not in room.")
  1845. # Only allow up to 20 events to be retrieved per request.
  1846. limit = min(limit, 20)
  1847. missing_events = await self.store.get_missing_events(
  1848. room_id=room_id,
  1849. earliest_events=earliest_events,
  1850. latest_events=latest_events,
  1851. limit=limit,
  1852. )
  1853. missing_events = await filter_events_for_server(
  1854. self.storage, origin, missing_events
  1855. )
  1856. return missing_events
  1857. async def do_auth(
  1858. self,
  1859. origin: str,
  1860. event: EventBase,
  1861. context: EventContext,
  1862. auth_events: StateMap[EventBase],
  1863. ) -> EventContext:
  1864. """
  1865. Args:
  1866. origin:
  1867. event:
  1868. context:
  1869. auth_events:
  1870. Map from (event_type, state_key) to event
  1871. Normally, our calculated auth_events based on the state of the room
  1872. at the event's position in the DAG, though occasionally (eg if the
  1873. event is an outlier), may be the auth events claimed by the remote
  1874. server.
  1875. Also NB that this function adds entries to it.
  1876. Returns:
  1877. updated context object
  1878. """
  1879. room_version = await self.store.get_room_version_id(event.room_id)
  1880. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1881. try:
  1882. context = await self._update_auth_events_and_context_for_auth(
  1883. origin, event, context, auth_events
  1884. )
  1885. except Exception:
  1886. # We don't really mind if the above fails, so lets not fail
  1887. # processing if it does. However, it really shouldn't fail so
  1888. # let's still log as an exception since we'll still want to fix
  1889. # any bugs.
  1890. logger.exception(
  1891. "Failed to double check auth events for %s with remote. "
  1892. "Ignoring failure and continuing processing of event.",
  1893. event.event_id,
  1894. )
  1895. try:
  1896. event_auth.check(room_version_obj, event, auth_events=auth_events)
  1897. except AuthError as e:
  1898. logger.warning("Failed auth resolution for %r because %s", event, e)
  1899. context.rejected = RejectedReason.AUTH_ERROR
  1900. return context
  1901. async def _update_auth_events_and_context_for_auth(
  1902. self,
  1903. origin: str,
  1904. event: EventBase,
  1905. context: EventContext,
  1906. auth_events: StateMap[EventBase],
  1907. ) -> EventContext:
  1908. """Helper for do_auth. See there for docs.
  1909. Checks whether a given event has the expected auth events. If it
  1910. doesn't then we talk to the remote server to compare state to see if
  1911. we can come to a consensus (e.g. if one server missed some valid
  1912. state).
  1913. This attempts to resolve any potential divergence of state between
  1914. servers, but is not essential and so failures should not block further
  1915. processing of the event.
  1916. Args:
  1917. origin:
  1918. event:
  1919. context:
  1920. auth_events:
  1921. Map from (event_type, state_key) to event
  1922. Normally, our calculated auth_events based on the state of the room
  1923. at the event's position in the DAG, though occasionally (eg if the
  1924. event is an outlier), may be the auth events claimed by the remote
  1925. server.
  1926. Also NB that this function adds entries to it.
  1927. Returns:
  1928. updated context
  1929. """
  1930. event_auth_events = set(event.auth_event_ids())
  1931. # missing_auth is the set of the event's auth_events which we don't yet have
  1932. # in auth_events.
  1933. missing_auth = event_auth_events.difference(
  1934. e.event_id for e in auth_events.values()
  1935. )
  1936. # if we have missing events, we need to fetch those events from somewhere.
  1937. #
  1938. # we start by checking if they are in the store, and then try calling /event_auth/.
  1939. if missing_auth:
  1940. have_events = await self.store.have_seen_events(missing_auth)
  1941. logger.debug("Events %s are in the store", have_events)
  1942. missing_auth.difference_update(have_events)
  1943. if missing_auth:
  1944. # If we don't have all the auth events, we need to get them.
  1945. logger.info("auth_events contains unknown events: %s", missing_auth)
  1946. try:
  1947. try:
  1948. remote_auth_chain = await self.federation_client.get_event_auth(
  1949. origin, event.room_id, event.event_id
  1950. )
  1951. except RequestSendFailed as e1:
  1952. # The other side isn't around or doesn't implement the
  1953. # endpoint, so lets just bail out.
  1954. logger.info("Failed to get event auth from remote: %s", e1)
  1955. return context
  1956. seen_remotes = await self.store.have_seen_events(
  1957. [e.event_id for e in remote_auth_chain]
  1958. )
  1959. for e in remote_auth_chain:
  1960. if e.event_id in seen_remotes:
  1961. continue
  1962. if e.event_id == event.event_id:
  1963. continue
  1964. try:
  1965. auth_ids = e.auth_event_ids()
  1966. auth = {
  1967. (e.type, e.state_key): e
  1968. for e in remote_auth_chain
  1969. if e.event_id in auth_ids or e.type == EventTypes.Create
  1970. }
  1971. e.internal_metadata.outlier = True
  1972. logger.debug(
  1973. "do_auth %s missing_auth: %s", event.event_id, e.event_id
  1974. )
  1975. await self._handle_new_event(origin, e, auth_events=auth)
  1976. if e.event_id in event_auth_events:
  1977. auth_events[(e.type, e.state_key)] = e
  1978. except AuthError:
  1979. pass
  1980. except Exception:
  1981. logger.exception("Failed to get auth chain")
  1982. if event.internal_metadata.is_outlier():
  1983. # XXX: given that, for an outlier, we'll be working with the
  1984. # event's *claimed* auth events rather than those we calculated:
  1985. # (a) is there any point in this test, since different_auth below will
  1986. # obviously be empty
  1987. # (b) alternatively, why don't we do it earlier?
  1988. logger.info("Skipping auth_event fetch for outlier")
  1989. return context
  1990. different_auth = event_auth_events.difference(
  1991. e.event_id for e in auth_events.values()
  1992. )
  1993. if not different_auth:
  1994. return context
  1995. logger.info(
  1996. "auth_events refers to events which are not in our calculated auth "
  1997. "chain: %s",
  1998. different_auth,
  1999. )
  2000. # XXX: currently this checks for redactions but I'm not convinced that is
  2001. # necessary?
  2002. different_events = await self.store.get_events_as_list(different_auth)
  2003. for d in different_events:
  2004. if d.room_id != event.room_id:
  2005. logger.warning(
  2006. "Event %s refers to auth_event %s which is in a different room",
  2007. event.event_id,
  2008. d.event_id,
  2009. )
  2010. # don't attempt to resolve the claimed auth events against our own
  2011. # in this case: just use our own auth events.
  2012. #
  2013. # XXX: should we reject the event in this case? It feels like we should,
  2014. # but then shouldn't we also do so if we've failed to fetch any of the
  2015. # auth events?
  2016. return context
  2017. # now we state-resolve between our own idea of the auth events, and the remote's
  2018. # idea of them.
  2019. local_state = auth_events.values()
  2020. remote_auth_events = dict(auth_events)
  2021. remote_auth_events.update({(d.type, d.state_key): d for d in different_events})
  2022. remote_state = remote_auth_events.values()
  2023. room_version = await self.store.get_room_version_id(event.room_id)
  2024. new_state = await self.state_handler.resolve_events(
  2025. room_version, (local_state, remote_state), event
  2026. )
  2027. logger.info(
  2028. "After state res: updating auth_events with new state %s",
  2029. {
  2030. (d.type, d.state_key): d.event_id
  2031. for d in new_state.values()
  2032. if auth_events.get((d.type, d.state_key)) != d
  2033. },
  2034. )
  2035. auth_events.update(new_state)
  2036. context = await self._update_context_for_auth_events(
  2037. event, context, auth_events
  2038. )
  2039. return context
  2040. async def _update_context_for_auth_events(
  2041. self, event: EventBase, context: EventContext, auth_events: StateMap[EventBase]
  2042. ) -> EventContext:
  2043. """Update the state_ids in an event context after auth event resolution,
  2044. storing the changes as a new state group.
  2045. Args:
  2046. event: The event we're handling the context for
  2047. context: initial event context
  2048. auth_events: Events to update in the event context.
  2049. Returns:
  2050. new event context
  2051. """
  2052. # exclude the state key of the new event from the current_state in the context.
  2053. if event.is_state():
  2054. event_key = (event.type, event.state_key) # type: Optional[Tuple[str, str]]
  2055. else:
  2056. event_key = None
  2057. state_updates = {
  2058. k: a.event_id for k, a in auth_events.items() if k != event_key
  2059. }
  2060. current_state_ids = await context.get_current_state_ids()
  2061. current_state_ids = dict(current_state_ids) # type: ignore
  2062. current_state_ids.update(state_updates)
  2063. prev_state_ids = await context.get_prev_state_ids()
  2064. prev_state_ids = dict(prev_state_ids)
  2065. prev_state_ids.update({k: a.event_id for k, a in auth_events.items()})
  2066. # create a new state group as a delta from the existing one.
  2067. prev_group = context.state_group
  2068. state_group = await self.state_store.store_state_group(
  2069. event.event_id,
  2070. event.room_id,
  2071. prev_group=prev_group,
  2072. delta_ids=state_updates,
  2073. current_state_ids=current_state_ids,
  2074. )
  2075. return EventContext.with_state(
  2076. state_group=state_group,
  2077. state_group_before_event=context.state_group_before_event,
  2078. current_state_ids=current_state_ids,
  2079. prev_state_ids=prev_state_ids,
  2080. prev_group=prev_group,
  2081. delta_ids=state_updates,
  2082. )
  2083. async def construct_auth_difference(
  2084. self, local_auth: Iterable[EventBase], remote_auth: Iterable[EventBase]
  2085. ) -> Dict:
  2086. """ Given a local and remote auth chain, find the differences. This
  2087. assumes that we have already processed all events in remote_auth
  2088. Params:
  2089. local_auth (list)
  2090. remote_auth (list)
  2091. Returns:
  2092. dict
  2093. """
  2094. logger.debug("construct_auth_difference Start!")
  2095. # TODO: Make sure we are OK with local_auth or remote_auth having more
  2096. # auth events in them than strictly necessary.
  2097. def sort_fun(ev):
  2098. return ev.depth, ev.event_id
  2099. logger.debug("construct_auth_difference after sort_fun!")
  2100. # We find the differences by starting at the "bottom" of each list
  2101. # and iterating up on both lists. The lists are ordered by depth and
  2102. # then event_id, we iterate up both lists until we find the event ids
  2103. # don't match. Then we look at depth/event_id to see which side is
  2104. # missing that event, and iterate only up that list. Repeat.
  2105. remote_list = list(remote_auth)
  2106. remote_list.sort(key=sort_fun)
  2107. local_list = list(local_auth)
  2108. local_list.sort(key=sort_fun)
  2109. local_iter = iter(local_list)
  2110. remote_iter = iter(remote_list)
  2111. logger.debug("construct_auth_difference before get_next!")
  2112. def get_next(it, opt=None):
  2113. try:
  2114. return next(it)
  2115. except Exception:
  2116. return opt
  2117. current_local = get_next(local_iter)
  2118. current_remote = get_next(remote_iter)
  2119. logger.debug("construct_auth_difference before while")
  2120. missing_remotes = []
  2121. missing_locals = []
  2122. while current_local or current_remote:
  2123. if current_remote is None:
  2124. missing_locals.append(current_local)
  2125. current_local = get_next(local_iter)
  2126. continue
  2127. if current_local is None:
  2128. missing_remotes.append(current_remote)
  2129. current_remote = get_next(remote_iter)
  2130. continue
  2131. if current_local.event_id == current_remote.event_id:
  2132. current_local = get_next(local_iter)
  2133. current_remote = get_next(remote_iter)
  2134. continue
  2135. if current_local.depth < current_remote.depth:
  2136. missing_locals.append(current_local)
  2137. current_local = get_next(local_iter)
  2138. continue
  2139. if current_local.depth > current_remote.depth:
  2140. missing_remotes.append(current_remote)
  2141. current_remote = get_next(remote_iter)
  2142. continue
  2143. # They have the same depth, so we fall back to the event_id order
  2144. if current_local.event_id < current_remote.event_id:
  2145. missing_locals.append(current_local)
  2146. current_local = get_next(local_iter)
  2147. if current_local.event_id > current_remote.event_id:
  2148. missing_remotes.append(current_remote)
  2149. current_remote = get_next(remote_iter)
  2150. continue
  2151. logger.debug("construct_auth_difference after while")
  2152. # missing locals should be sent to the server
  2153. # We should find why we are missing remotes, as they will have been
  2154. # rejected.
  2155. # Remove events from missing_remotes if they are referencing a missing
  2156. # remote. We only care about the "root" rejected ones.
  2157. missing_remote_ids = [e.event_id for e in missing_remotes]
  2158. base_remote_rejected = list(missing_remotes)
  2159. for e in missing_remotes:
  2160. for e_id in e.auth_event_ids():
  2161. if e_id in missing_remote_ids:
  2162. try:
  2163. base_remote_rejected.remove(e)
  2164. except ValueError:
  2165. pass
  2166. reason_map = {}
  2167. for e in base_remote_rejected:
  2168. reason = await self.store.get_rejection_reason(e.event_id)
  2169. if reason is None:
  2170. # TODO: e is not in the current state, so we should
  2171. # construct some proof of that.
  2172. continue
  2173. reason_map[e.event_id] = reason
  2174. logger.debug("construct_auth_difference returning")
  2175. return {
  2176. "auth_chain": local_auth,
  2177. "rejects": {
  2178. e.event_id: {"reason": reason_map[e.event_id], "proof": None}
  2179. for e in base_remote_rejected
  2180. },
  2181. "missing": [e.event_id for e in missing_locals],
  2182. }
  2183. @log_function
  2184. async def exchange_third_party_invite(
  2185. self, sender_user_id, target_user_id, room_id, signed
  2186. ):
  2187. third_party_invite = {"signed": signed}
  2188. event_dict = {
  2189. "type": EventTypes.Member,
  2190. "content": {
  2191. "membership": Membership.INVITE,
  2192. "third_party_invite": third_party_invite,
  2193. },
  2194. "room_id": room_id,
  2195. "sender": sender_user_id,
  2196. "state_key": target_user_id,
  2197. }
  2198. if await self.auth.check_host_in_room(room_id, self.hs.hostname):
  2199. room_version = await self.store.get_room_version_id(room_id)
  2200. builder = self.event_builder_factory.new(room_version, event_dict)
  2201. EventValidator().validate_builder(builder)
  2202. event, context = await self.event_creation_handler.create_new_client_event(
  2203. builder=builder
  2204. )
  2205. event_allowed = await self.third_party_event_rules.check_event_allowed(
  2206. event, context
  2207. )
  2208. if not event_allowed:
  2209. logger.info(
  2210. "Creation of threepid invite %s forbidden by third-party rules",
  2211. event,
  2212. )
  2213. raise SynapseError(
  2214. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  2215. )
  2216. event, context = await self.add_display_name_to_third_party_invite(
  2217. room_version, event_dict, event, context
  2218. )
  2219. EventValidator().validate_new(event, self.config)
  2220. # We need to tell the transaction queue to send this out, even
  2221. # though the sender isn't a local user.
  2222. event.internal_metadata.send_on_behalf_of = self.hs.hostname
  2223. try:
  2224. await self.auth.check_from_context(room_version, event, context)
  2225. except AuthError as e:
  2226. logger.warning("Denying new third party invite %r because %s", event, e)
  2227. raise e
  2228. await self._check_signature(event, context)
  2229. # We retrieve the room member handler here as to not cause a cyclic dependency
  2230. member_handler = self.hs.get_room_member_handler()
  2231. await member_handler.send_membership_event(None, event, context)
  2232. else:
  2233. destinations = {x.split(":", 1)[-1] for x in (sender_user_id, room_id)}
  2234. await self.federation_client.forward_third_party_invite(
  2235. destinations, room_id, event_dict
  2236. )
  2237. async def on_exchange_third_party_invite_request(
  2238. self, room_id: str, event_dict: JsonDict
  2239. ) -> None:
  2240. """Handle an exchange_third_party_invite request from a remote server
  2241. The remote server will call this when it wants to turn a 3pid invite
  2242. into a normal m.room.member invite.
  2243. Args:
  2244. room_id: The ID of the room.
  2245. event_dict (dict[str, Any]): Dictionary containing the event body.
  2246. """
  2247. room_version = await self.store.get_room_version_id(room_id)
  2248. # NB: event_dict has a particular specced format we might need to fudge
  2249. # if we change event formats too much.
  2250. builder = self.event_builder_factory.new(room_version, event_dict)
  2251. event, context = await self.event_creation_handler.create_new_client_event(
  2252. builder=builder
  2253. )
  2254. event_allowed = await self.third_party_event_rules.check_event_allowed(
  2255. event, context
  2256. )
  2257. if not event_allowed:
  2258. logger.warning(
  2259. "Exchange of threepid invite %s forbidden by third-party rules", event
  2260. )
  2261. raise SynapseError(
  2262. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  2263. )
  2264. event, context = await self.add_display_name_to_third_party_invite(
  2265. room_version, event_dict, event, context
  2266. )
  2267. try:
  2268. await self.auth.check_from_context(room_version, event, context)
  2269. except AuthError as e:
  2270. logger.warning("Denying third party invite %r because %s", event, e)
  2271. raise e
  2272. await self._check_signature(event, context)
  2273. # We need to tell the transaction queue to send this out, even
  2274. # though the sender isn't a local user.
  2275. event.internal_metadata.send_on_behalf_of = get_domain_from_id(event.sender)
  2276. # We retrieve the room member handler here as to not cause a cyclic dependency
  2277. member_handler = self.hs.get_room_member_handler()
  2278. await member_handler.send_membership_event(None, event, context)
  2279. async def add_display_name_to_third_party_invite(
  2280. self, room_version, event_dict, event, context
  2281. ):
  2282. key = (
  2283. EventTypes.ThirdPartyInvite,
  2284. event.content["third_party_invite"]["signed"]["token"],
  2285. )
  2286. original_invite = None
  2287. prev_state_ids = await context.get_prev_state_ids()
  2288. original_invite_id = prev_state_ids.get(key)
  2289. if original_invite_id:
  2290. original_invite = await self.store.get_event(
  2291. original_invite_id, allow_none=True
  2292. )
  2293. if original_invite:
  2294. # If the m.room.third_party_invite event's content is empty, it means the
  2295. # invite has been revoked. In this case, we don't have to raise an error here
  2296. # because the auth check will fail on the invite (because it's not able to
  2297. # fetch public keys from the m.room.third_party_invite event's content, which
  2298. # is empty).
  2299. display_name = original_invite.content.get("display_name")
  2300. event_dict["content"]["third_party_invite"]["display_name"] = display_name
  2301. else:
  2302. logger.info(
  2303. "Could not find invite event for third_party_invite: %r", event_dict
  2304. )
  2305. # We don't discard here as this is not the appropriate place to do
  2306. # auth checks. If we need the invite and don't have it then the
  2307. # auth check code will explode appropriately.
  2308. builder = self.event_builder_factory.new(room_version, event_dict)
  2309. EventValidator().validate_builder(builder)
  2310. event, context = await self.event_creation_handler.create_new_client_event(
  2311. builder=builder
  2312. )
  2313. EventValidator().validate_new(event, self.config)
  2314. return (event, context)
  2315. async def _check_signature(self, event, context):
  2316. """
  2317. Checks that the signature in the event is consistent with its invite.
  2318. Args:
  2319. event (Event): The m.room.member event to check
  2320. context (EventContext):
  2321. Raises:
  2322. AuthError: if signature didn't match any keys, or key has been
  2323. revoked,
  2324. SynapseError: if a transient error meant a key couldn't be checked
  2325. for revocation.
  2326. """
  2327. signed = event.content["third_party_invite"]["signed"]
  2328. token = signed["token"]
  2329. prev_state_ids = await context.get_prev_state_ids()
  2330. invite_event_id = prev_state_ids.get((EventTypes.ThirdPartyInvite, token))
  2331. invite_event = None
  2332. if invite_event_id:
  2333. invite_event = await self.store.get_event(invite_event_id, allow_none=True)
  2334. if not invite_event:
  2335. raise AuthError(403, "Could not find invite")
  2336. logger.debug("Checking auth on event %r", event.content)
  2337. last_exception = None # type: Optional[Exception]
  2338. # for each public key in the 3pid invite event
  2339. for public_key_object in self.hs.get_auth().get_public_keys(invite_event):
  2340. try:
  2341. # for each sig on the third_party_invite block of the actual invite
  2342. for server, signature_block in signed["signatures"].items():
  2343. for key_name, encoded_signature in signature_block.items():
  2344. if not key_name.startswith("ed25519:"):
  2345. continue
  2346. logger.debug(
  2347. "Attempting to verify sig with key %s from %r "
  2348. "against pubkey %r",
  2349. key_name,
  2350. server,
  2351. public_key_object,
  2352. )
  2353. try:
  2354. public_key = public_key_object["public_key"]
  2355. verify_key = decode_verify_key_bytes(
  2356. key_name, decode_base64(public_key)
  2357. )
  2358. verify_signed_json(signed, server, verify_key)
  2359. logger.debug(
  2360. "Successfully verified sig with key %s from %r "
  2361. "against pubkey %r",
  2362. key_name,
  2363. server,
  2364. public_key_object,
  2365. )
  2366. except Exception:
  2367. logger.info(
  2368. "Failed to verify sig with key %s from %r "
  2369. "against pubkey %r",
  2370. key_name,
  2371. server,
  2372. public_key_object,
  2373. )
  2374. raise
  2375. try:
  2376. if "key_validity_url" in public_key_object:
  2377. await self._check_key_revocation(
  2378. public_key, public_key_object["key_validity_url"]
  2379. )
  2380. except Exception:
  2381. logger.info(
  2382. "Failed to query key_validity_url %s",
  2383. public_key_object["key_validity_url"],
  2384. )
  2385. raise
  2386. return
  2387. except Exception as e:
  2388. last_exception = e
  2389. if last_exception is None:
  2390. # we can only get here if get_public_keys() returned an empty list
  2391. # TODO: make this better
  2392. raise RuntimeError("no public key in invite event")
  2393. raise last_exception
  2394. async def _check_key_revocation(self, public_key, url):
  2395. """
  2396. Checks whether public_key has been revoked.
  2397. Args:
  2398. public_key (str): base-64 encoded public key.
  2399. url (str): Key revocation URL.
  2400. Raises:
  2401. AuthError: if they key has been revoked.
  2402. SynapseError: if a transient error meant a key couldn't be checked
  2403. for revocation.
  2404. """
  2405. try:
  2406. response = await self.http_client.get_json(url, {"public_key": public_key})
  2407. except Exception:
  2408. raise SynapseError(502, "Third party certificate could not be checked")
  2409. if "valid" not in response or not response["valid"]:
  2410. raise AuthError(403, "Third party certificate was invalid")
  2411. async def persist_events_and_notify(
  2412. self,
  2413. event_and_contexts: Sequence[Tuple[EventBase, EventContext]],
  2414. backfilled: bool = False,
  2415. ) -> int:
  2416. """Persists events and tells the notifier/pushers about them, if
  2417. necessary.
  2418. Args:
  2419. event_and_contexts:
  2420. backfilled: Whether these events are a result of
  2421. backfilling or not
  2422. """
  2423. if self.config.worker.writers.events != self._instance_name:
  2424. result = await self._send_events(
  2425. instance_name=self.config.worker.writers.events,
  2426. store=self.store,
  2427. event_and_contexts=event_and_contexts,
  2428. backfilled=backfilled,
  2429. )
  2430. return result["max_stream_id"]
  2431. else:
  2432. max_stream_id = await self.storage.persistence.persist_events(
  2433. event_and_contexts, backfilled=backfilled
  2434. )
  2435. if self._ephemeral_messages_enabled:
  2436. for (event, context) in event_and_contexts:
  2437. # If there's an expiry timestamp on the event, schedule its expiry.
  2438. self._message_handler.maybe_schedule_expiry(event)
  2439. if not backfilled: # Never notify for backfilled events
  2440. for event, _ in event_and_contexts:
  2441. await self._notify_persisted_event(event, max_stream_id)
  2442. return max_stream_id
  2443. async def _notify_persisted_event(
  2444. self, event: EventBase, max_stream_id: int
  2445. ) -> None:
  2446. """Checks to see if notifier/pushers should be notified about the
  2447. event or not.
  2448. Args:
  2449. event:
  2450. max_stream_id: The max_stream_id returned by persist_events
  2451. """
  2452. extra_users = []
  2453. if event.type == EventTypes.Member:
  2454. target_user_id = event.state_key
  2455. # We notify for memberships if its an invite for one of our
  2456. # users
  2457. if event.internal_metadata.is_outlier():
  2458. if event.membership != Membership.INVITE:
  2459. if not self.is_mine_id(target_user_id):
  2460. return
  2461. target_user = UserID.from_string(target_user_id)
  2462. extra_users.append(target_user)
  2463. elif event.internal_metadata.is_outlier():
  2464. return
  2465. event_stream_id = event.internal_metadata.stream_ordering
  2466. self.notifier.on_new_room_event(
  2467. event, event_stream_id, max_stream_id, extra_users=extra_users
  2468. )
  2469. await self.pusher_pool.on_new_notifications(event_stream_id, max_stream_id)
  2470. async def _clean_room_for_join(self, room_id: str) -> None:
  2471. """Called to clean up any data in DB for a given room, ready for the
  2472. server to join the room.
  2473. Args:
  2474. room_id
  2475. """
  2476. if self.config.worker_app:
  2477. await self._clean_room_for_join_client(room_id)
  2478. else:
  2479. await self.store.clean_room_for_join(room_id)
  2480. async def user_joined_room(self, user: UserID, room_id: str) -> None:
  2481. """Called when a new user has joined the room
  2482. """
  2483. if self.config.worker_app:
  2484. await self._notify_user_membership_change(
  2485. room_id=room_id, user_id=user.to_string(), change="joined"
  2486. )
  2487. else:
  2488. user_joined_room(self.distributor, user, room_id)
  2489. async def get_room_complexity(
  2490. self, remote_room_hosts: List[str], room_id: str
  2491. ) -> Optional[dict]:
  2492. """
  2493. Fetch the complexity of a remote room over federation.
  2494. Args:
  2495. remote_room_hosts (list[str]): The remote servers to ask.
  2496. room_id (str): The room ID to ask about.
  2497. Returns:
  2498. Dict contains the complexity
  2499. metric versions, while None means we could not fetch the complexity.
  2500. """
  2501. for host in remote_room_hosts:
  2502. res = await self.federation_client.get_room_complexity(host, room_id)
  2503. # We got a result, return it.
  2504. if res:
  2505. return res
  2506. # We fell off the bottom, couldn't get the complexity from anyone. Oh
  2507. # well.
  2508. return None