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

2380 lines
96 KiB

  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import collections
  15. import itertools
  16. import logging
  17. from http import HTTPStatus
  18. from typing import (
  19. TYPE_CHECKING,
  20. Collection,
  21. Container,
  22. Dict,
  23. Iterable,
  24. List,
  25. Optional,
  26. Sequence,
  27. Set,
  28. Tuple,
  29. )
  30. from prometheus_client import Counter, Histogram
  31. from synapse import event_auth
  32. from synapse.api.constants import (
  33. EventContentFields,
  34. EventTypes,
  35. GuestAccess,
  36. Membership,
  37. RejectedReason,
  38. RoomEncryptionAlgorithms,
  39. )
  40. from synapse.api.errors import (
  41. AuthError,
  42. Codes,
  43. EventSizeError,
  44. FederationError,
  45. FederationPullAttemptBackoffError,
  46. HttpResponseException,
  47. PartialStateConflictError,
  48. RequestSendFailed,
  49. SynapseError,
  50. )
  51. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion, RoomVersions
  52. from synapse.event_auth import (
  53. auth_types_for_event,
  54. check_state_dependent_auth_rules,
  55. check_state_independent_auth_rules,
  56. validate_event_for_room_version,
  57. )
  58. from synapse.events import EventBase
  59. from synapse.events.snapshot import EventContext, UnpersistedEventContextBase
  60. from synapse.federation.federation_client import InvalidResponseError, PulledPduInfo
  61. from synapse.logging.context import nested_logging_context
  62. from synapse.logging.opentracing import (
  63. SynapseTags,
  64. set_tag,
  65. start_active_span,
  66. tag_args,
  67. trace,
  68. )
  69. from synapse.metrics.background_process_metrics import run_as_background_process
  70. from synapse.replication.http.devices import (
  71. ReplicationMultiUserDevicesResyncRestServlet,
  72. )
  73. from synapse.replication.http.federation import (
  74. ReplicationFederationSendEventsRestServlet,
  75. )
  76. from synapse.state import StateResolutionStore
  77. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  78. from synapse.types import (
  79. PersistedEventPosition,
  80. RoomStreamToken,
  81. StateMap,
  82. StrCollection,
  83. UserID,
  84. get_domain_from_id,
  85. )
  86. from synapse.types.state import StateFilter
  87. from synapse.util.async_helpers import Linearizer, concurrently_execute
  88. from synapse.util.iterutils import batch_iter, partition
  89. from synapse.util.retryutils import NotRetryingDestination
  90. from synapse.util.stringutils import shortstr
  91. if TYPE_CHECKING:
  92. from synapse.server import HomeServer
  93. logger = logging.getLogger(__name__)
  94. soft_failed_event_counter = Counter(
  95. "synapse_federation_soft_failed_events_total",
  96. "Events received over federation that we marked as soft_failed",
  97. )
  98. # Added to debug performance and track progress on optimizations
  99. backfill_processing_after_timer = Histogram(
  100. "synapse_federation_backfill_processing_after_time_seconds",
  101. "sec",
  102. [],
  103. buckets=(
  104. 0.1,
  105. 0.25,
  106. 0.5,
  107. 1.0,
  108. 2.5,
  109. 5.0,
  110. 7.5,
  111. 10.0,
  112. 15.0,
  113. 20.0,
  114. 25.0,
  115. 30.0,
  116. 40.0,
  117. 50.0,
  118. 60.0,
  119. 80.0,
  120. 100.0,
  121. 120.0,
  122. 150.0,
  123. 180.0,
  124. "+Inf",
  125. ),
  126. )
  127. class FederationEventHandler:
  128. """Handles events that originated from federation.
  129. Responsible for handing incoming events and passing them on to the rest
  130. of the homeserver (including auth and state conflict resolutions)
  131. """
  132. def __init__(self, hs: "HomeServer"):
  133. self._clock = hs.get_clock()
  134. self._store = hs.get_datastores().main
  135. self._storage_controllers = hs.get_storage_controllers()
  136. self._state_storage_controller = self._storage_controllers.state
  137. self._state_handler = hs.get_state_handler()
  138. self._event_creation_handler = hs.get_event_creation_handler()
  139. self._event_auth_handler = hs.get_event_auth_handler()
  140. self._message_handler = hs.get_message_handler()
  141. self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()
  142. self._state_resolution_handler = hs.get_state_resolution_handler()
  143. # avoid a circular dependency by deferring execution here
  144. self._get_room_member_handler = hs.get_room_member_handler
  145. self._federation_client = hs.get_federation_client()
  146. self._third_party_event_rules = (
  147. hs.get_module_api_callbacks().third_party_event_rules
  148. )
  149. self._notifier = hs.get_notifier()
  150. self._is_mine_id = hs.is_mine_id
  151. self._is_mine_server_name = hs.is_mine_server_name
  152. self._server_name = hs.hostname
  153. self._instance_name = hs.get_instance_name()
  154. self._config = hs.config
  155. self._ephemeral_messages_enabled = hs.config.server.enable_ephemeral_messages
  156. self._send_events = ReplicationFederationSendEventsRestServlet.make_client(hs)
  157. if hs.config.worker.worker_app:
  158. self._multi_user_device_resync = (
  159. ReplicationMultiUserDevicesResyncRestServlet.make_client(hs)
  160. )
  161. else:
  162. self._device_list_updater = hs.get_device_handler().device_list_updater
  163. # When joining a room we need to queue any events for that room up.
  164. # For each room, a list of (pdu, origin) tuples.
  165. # TODO: replace this with something more elegant, probably based around the
  166. # federation event staging area.
  167. self.room_queues: Dict[str, List[Tuple[EventBase, str]]] = {}
  168. self._room_pdu_linearizer = Linearizer("fed_room_pdu")
  169. async def on_receive_pdu(self, origin: str, pdu: EventBase) -> None:
  170. """Process a PDU received via a federation /send/ transaction
  171. Args:
  172. origin: server which initiated the /send/ transaction. Will
  173. be used to fetch missing events or state.
  174. pdu: received PDU
  175. """
  176. # We should never see any outliers here.
  177. assert not pdu.internal_metadata.outlier
  178. room_id = pdu.room_id
  179. event_id = pdu.event_id
  180. # We reprocess pdus when we have seen them only as outliers
  181. existing = await self._store.get_event(
  182. event_id, allow_none=True, allow_rejected=True
  183. )
  184. # FIXME: Currently we fetch an event again when we already have it
  185. # if it has been marked as an outlier.
  186. if existing:
  187. if not existing.internal_metadata.is_outlier():
  188. logger.info(
  189. "Ignoring received event %s which we have already seen", event_id
  190. )
  191. return
  192. if pdu.internal_metadata.is_outlier():
  193. logger.info(
  194. "Ignoring received outlier %s which we already have as an outlier",
  195. event_id,
  196. )
  197. return
  198. logger.info("De-outliering event %s", event_id)
  199. # do some initial sanity-checking of the event. In particular, make
  200. # sure it doesn't have hundreds of prev_events or auth_events, which
  201. # could cause a huge state resolution or cascade of event fetches.
  202. try:
  203. self._sanity_check_event(pdu)
  204. except SynapseError as err:
  205. logger.warning("Received event failed sanity checks")
  206. raise FederationError("ERROR", err.code, err.msg, affected=pdu.event_id)
  207. # If we are currently in the process of joining this room, then we
  208. # queue up events for later processing.
  209. if room_id in self.room_queues:
  210. logger.info(
  211. "Queuing PDU from %s for now: join in progress",
  212. origin,
  213. )
  214. self.room_queues[room_id].append((pdu, origin))
  215. return
  216. # If we're not in the room just ditch the event entirely. This is
  217. # probably an old server that has come back and thinks we're still in
  218. # the room (or we've been rejoined to the room by a state reset).
  219. #
  220. # Note that if we were never in the room then we would have already
  221. # dropped the event, since we wouldn't know the room version.
  222. is_in_room = await self._event_auth_handler.is_host_in_room(
  223. room_id, self._server_name
  224. )
  225. if not is_in_room:
  226. logger.info(
  227. "Ignoring PDU from %s as we're not in the room",
  228. origin,
  229. )
  230. return None
  231. # Try to fetch any missing prev events to fill in gaps in the graph
  232. prevs = set(pdu.prev_event_ids())
  233. seen = await self._store.have_events_in_timeline(prevs)
  234. missing_prevs = prevs - seen
  235. if missing_prevs:
  236. # We only backfill backwards to the min depth.
  237. min_depth = await self._store.get_min_depth(pdu.room_id)
  238. logger.debug("min_depth: %d", min_depth)
  239. if min_depth is not None and pdu.depth > min_depth:
  240. # If we're missing stuff, ensure we only fetch stuff one
  241. # at a time.
  242. logger.info(
  243. "Acquiring room lock to fetch %d missing prev_events: %s",
  244. len(missing_prevs),
  245. shortstr(missing_prevs),
  246. )
  247. async with self._room_pdu_linearizer.queue(pdu.room_id):
  248. logger.info(
  249. "Acquired room lock to fetch %d missing prev_events",
  250. len(missing_prevs),
  251. )
  252. try:
  253. await self._get_missing_events_for_pdu(
  254. origin, pdu, prevs, min_depth
  255. )
  256. except Exception as e:
  257. raise Exception(
  258. "Error fetching missing prev_events for %s: %s"
  259. % (event_id, e)
  260. ) from e
  261. # Update the set of things we've seen after trying to
  262. # fetch the missing stuff
  263. seen = await self._store.have_events_in_timeline(prevs)
  264. missing_prevs = prevs - seen
  265. if not missing_prevs:
  266. logger.info("Found all missing prev_events")
  267. if missing_prevs:
  268. # since this event was pushed to us, it is possible for it to
  269. # become the only forward-extremity in the room, and we would then
  270. # trust its state to be the state for the whole room. This is very
  271. # bad. Further, if the event was pushed to us, there is no excuse
  272. # for us not to have all the prev_events. (XXX: apart from
  273. # min_depth?)
  274. #
  275. # We therefore reject any such events.
  276. logger.warning(
  277. "Rejecting: failed to fetch %d prev events: %s",
  278. len(missing_prevs),
  279. shortstr(missing_prevs),
  280. )
  281. raise FederationError(
  282. "ERROR",
  283. 403,
  284. (
  285. "Your server isn't divulging details about prev_events "
  286. "referenced in this event."
  287. ),
  288. affected=pdu.event_id,
  289. )
  290. try:
  291. context = await self._state_handler.compute_event_context(pdu)
  292. await self._process_received_pdu(origin, pdu, context)
  293. except PartialStateConflictError:
  294. # The room was un-partial stated while we were processing the PDU.
  295. # Try once more, with full state this time.
  296. logger.info(
  297. "Room %s was un-partial stated while processing the PDU, trying again.",
  298. room_id,
  299. )
  300. context = await self._state_handler.compute_event_context(pdu)
  301. await self._process_received_pdu(origin, pdu, context)
  302. async def on_send_membership_event(
  303. self, origin: str, event: EventBase
  304. ) -> Tuple[EventBase, EventContext]:
  305. """
  306. We have received a join/leave/knock event for a room via send_join/leave/knock.
  307. Verify that event and send it into the room on the remote homeserver's behalf.
  308. This is quite similar to on_receive_pdu, with the following principal
  309. differences:
  310. * only membership events are permitted (and only events with
  311. sender==state_key -- ie, no kicks or bans)
  312. * *We* send out the event on behalf of the remote server.
  313. * We enforce the membership restrictions of restricted rooms.
  314. * Rejected events result in an exception rather than being stored.
  315. There are also other differences, however it is not clear if these are by
  316. design or omission. In particular, we do not attempt to backfill any missing
  317. prev_events.
  318. Args:
  319. origin: The homeserver of the remote (joining/invited/knocking) user.
  320. event: The member event that has been signed by the remote homeserver.
  321. Returns:
  322. The event and context of the event after inserting it into the room graph.
  323. Raises:
  324. RuntimeError if any prev_events are missing
  325. SynapseError if the event is not accepted into the room
  326. PartialStateConflictError if the room was un-partial stated in between
  327. computing the state at the event and persisting it. The caller should
  328. retry exactly once in this case.
  329. """
  330. logger.debug(
  331. "on_send_membership_event: Got event: %s, signatures: %s",
  332. event.event_id,
  333. event.signatures,
  334. )
  335. if get_domain_from_id(event.sender) != origin:
  336. logger.info(
  337. "Got send_membership request for user %r from different origin %s",
  338. event.sender,
  339. origin,
  340. )
  341. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  342. if event.sender != event.state_key:
  343. raise SynapseError(400, "state_key and sender must match", Codes.BAD_JSON)
  344. assert not event.internal_metadata.outlier
  345. # Send this event on behalf of the other server.
  346. #
  347. # The remote server isn't a full participant in the room at this point, so
  348. # may not have an up-to-date list of the other homeservers participating in
  349. # the room, so we send it on their behalf.
  350. event.internal_metadata.send_on_behalf_of = origin
  351. context = await self._state_handler.compute_event_context(event)
  352. await self._check_event_auth(origin, event, context)
  353. if context.rejected:
  354. raise SynapseError(
  355. 403, f"{event.membership} event was rejected", Codes.FORBIDDEN
  356. )
  357. # for joins, we need to check the restrictions of restricted rooms
  358. if event.membership == Membership.JOIN:
  359. await self.check_join_restrictions(context, event)
  360. # for knock events, we run the third-party event rules. It's not entirely clear
  361. # why we don't do this for other sorts of membership events.
  362. if event.membership == Membership.KNOCK:
  363. event_allowed, _ = await self._third_party_event_rules.check_event_allowed(
  364. event, context
  365. )
  366. if not event_allowed:
  367. logger.info("Sending of knock %s forbidden by third-party rules", event)
  368. raise SynapseError(
  369. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  370. )
  371. # all looks good, we can persist the event.
  372. # First, precalculate the joined hosts so that the federation sender doesn't
  373. # need to.
  374. await self._event_creation_handler.cache_joined_hosts_for_events(
  375. [(event, context)]
  376. )
  377. await self._check_for_soft_fail(event, context=context, origin=origin)
  378. await self._run_push_actions_and_persist_event(event, context)
  379. return event, context
  380. async def check_join_restrictions(
  381. self,
  382. context: UnpersistedEventContextBase,
  383. event: EventBase,
  384. ) -> None:
  385. """Check that restrictions in restricted join rules are matched
  386. Called when we receive a join event via send_join.
  387. Raises an auth error if the restrictions are not matched.
  388. """
  389. prev_state_ids = await context.get_prev_state_ids()
  390. # Check if the user is already in the room or invited to the room.
  391. user_id = event.state_key
  392. prev_member_event_id = prev_state_ids.get((EventTypes.Member, user_id), None)
  393. prev_membership = None
  394. if prev_member_event_id:
  395. prev_member_event = await self._store.get_event(prev_member_event_id)
  396. prev_membership = prev_member_event.membership
  397. # Check if the member should be allowed access via membership in a space.
  398. await self._event_auth_handler.check_restricted_join_rules(
  399. prev_state_ids,
  400. event.room_version,
  401. user_id,
  402. prev_membership,
  403. )
  404. @trace
  405. async def process_remote_join(
  406. self,
  407. origin: str,
  408. room_id: str,
  409. auth_events: List[EventBase],
  410. state: List[EventBase],
  411. event: EventBase,
  412. room_version: RoomVersion,
  413. partial_state: bool,
  414. ) -> int:
  415. """Persists the events returned by a send_join
  416. Checks the auth chain is valid (and passes auth checks) for the
  417. state and event. Then persists all of the events.
  418. Notifies about the persisted events where appropriate.
  419. Args:
  420. origin: Where the events came from
  421. room_id:
  422. auth_events
  423. state
  424. event
  425. room_version: The room version we expect this room to have, and
  426. will raise if it doesn't match the version in the create event.
  427. partial_state: True if the state omits non-critical membership events
  428. Returns:
  429. The stream ID after which all events have been persisted.
  430. Raises:
  431. SynapseError if the response is in some way invalid.
  432. PartialStateConflictError if the homeserver is already in the room and it
  433. has been un-partial stated.
  434. """
  435. create_event = None
  436. for e in state:
  437. if (e.type, e.state_key) == (EventTypes.Create, ""):
  438. create_event = e
  439. break
  440. if create_event is None:
  441. # If the state doesn't have a create event then the room is
  442. # invalid, and it would fail auth checks anyway.
  443. raise SynapseError(400, "No create event in state")
  444. room_version_id = create_event.content.get(
  445. "room_version", RoomVersions.V1.identifier
  446. )
  447. if room_version.identifier != room_version_id:
  448. raise SynapseError(400, "Room version mismatch")
  449. # persist the auth chain and state events.
  450. #
  451. # any invalid events here will be marked as rejected, and we'll carry on.
  452. #
  453. # any events whose auth events are missing (ie, not in the send_join response,
  454. # and not already in our db) will just be ignored. This is correct behaviour,
  455. # because the reason that auth_events are missing might be due to us being
  456. # unable to validate their signatures. The fact that we can't validate their
  457. # signatures right now doesn't mean that we will *never* be able to, so it
  458. # is premature to reject them.
  459. #
  460. await self._auth_and_persist_outliers(
  461. room_id, itertools.chain(auth_events, state)
  462. )
  463. # and now persist the join event itself.
  464. logger.info(
  465. "Peristing join-via-remote %s (partial_state: %s)", event, partial_state
  466. )
  467. with nested_logging_context(suffix=event.event_id):
  468. if partial_state:
  469. # When handling a second partial state join into a partial state room,
  470. # the returned state will exclude the membership from the first join. To
  471. # preserve prior memberships, we try to compute the partial state before
  472. # the event ourselves if we know about any of the prev events.
  473. #
  474. # When we don't know about any of the prev events, it's fine to just use
  475. # the returned state, since the new join will create a new forward
  476. # extremity, and leave the forward extremity containing our prior
  477. # memberships alone.
  478. prev_event_ids = set(event.prev_event_ids())
  479. seen_event_ids = await self._store.have_events_in_timeline(
  480. prev_event_ids
  481. )
  482. missing_event_ids = prev_event_ids - seen_event_ids
  483. state_maps_to_resolve: List[StateMap[str]] = []
  484. # Fetch the state after the prev events that we know about.
  485. state_maps_to_resolve.extend(
  486. (
  487. await self._state_storage_controller.get_state_groups_ids(
  488. room_id, seen_event_ids, await_full_state=False
  489. )
  490. ).values()
  491. )
  492. # When there are prev events we do not have the state for, we state
  493. # resolve with the state returned by the remote homeserver.
  494. if missing_event_ids or len(state_maps_to_resolve) == 0:
  495. state_maps_to_resolve.append(
  496. {(e.type, e.state_key): e.event_id for e in state}
  497. )
  498. state_ids_before_event = (
  499. await self._state_resolution_handler.resolve_events_with_store(
  500. event.room_id,
  501. room_version.identifier,
  502. state_maps_to_resolve,
  503. event_map=None,
  504. state_res_store=StateResolutionStore(self._store),
  505. )
  506. )
  507. else:
  508. state_ids_before_event = {
  509. (e.type, e.state_key): e.event_id for e in state
  510. }
  511. context = await self._state_handler.compute_event_context(
  512. event,
  513. state_ids_before_event=state_ids_before_event,
  514. partial_state=partial_state,
  515. )
  516. await self._check_event_auth(origin, event, context)
  517. if context.rejected:
  518. raise SynapseError(403, "Join event was rejected")
  519. # the remote server is responsible for sending our join event to the rest
  520. # of the federation. Indeed, attempting to do so will result in problems
  521. # when we try to look up the state before the join (to get the server list)
  522. # and discover that we do not have it.
  523. event.internal_metadata.proactively_send = False
  524. stream_id_after_persist = await self.persist_events_and_notify(
  525. room_id, [(event, context)]
  526. )
  527. return stream_id_after_persist
  528. async def update_state_for_partial_state_event(
  529. self, destination: str, event: EventBase
  530. ) -> None:
  531. """Recalculate the state at an event as part of a de-partial-stating process
  532. Args:
  533. destination: server to request full state from
  534. event: partial-state event to be de-partial-stated
  535. Raises:
  536. FederationPullAttemptBackoffError if we are are deliberately not attempting
  537. to pull the given event over federation because we've already done so
  538. recently and are backing off.
  539. FederationError if we fail to request state from the remote server.
  540. """
  541. logger.info("Updating state for %s", event.event_id)
  542. with nested_logging_context(suffix=event.event_id):
  543. # if we have all the event's prev_events, then we can work out the
  544. # state based on their states. Otherwise, we request it from the destination
  545. # server.
  546. #
  547. # This is the same operation as we do when we receive a regular event
  548. # over federation.
  549. context = await self._compute_event_context_with_maybe_missing_prevs(
  550. destination, event
  551. )
  552. if context.partial_state:
  553. # this can happen if some or all of the event's prev_events still have
  554. # partial state. We were careful to only pick events from the db without
  555. # partial-state prev events, so that implies that a prev event has
  556. # been persisted (with partial state) since we did the query.
  557. #
  558. # So, let's just ignore `event` for now; when we re-run the db query
  559. # we should instead get its partial-state prev event, which we will
  560. # de-partial-state, and then come back to event.
  561. logger.warning(
  562. "%s still has prev_events with partial state: can't de-partial-state it yet",
  563. event.event_id,
  564. )
  565. return
  566. # since the state at this event has changed, we should now re-evaluate
  567. # whether it should have been rejected. We must already have all of the
  568. # auth events (from last time we went round this path), so there is no
  569. # need to pass the origin.
  570. await self._check_event_auth(None, event, context)
  571. await self._store.update_state_for_partial_state_event(event, context)
  572. self._state_storage_controller.notify_event_un_partial_stated(
  573. event.event_id
  574. )
  575. # Notify that there's a new row in the un_partial_stated_events stream.
  576. self._notifier.notify_replication()
  577. @trace
  578. async def backfill(
  579. self, dest: str, room_id: str, limit: int, extremities: StrCollection
  580. ) -> None:
  581. """Trigger a backfill request to `dest` for the given `room_id`
  582. This will attempt to get more events from the remote. If the other side
  583. has no new events to offer, this will return an empty list.
  584. As the events are received, we check their signatures, and also do some
  585. sanity-checking on them. If any of the backfilled events are invalid,
  586. this method throws a SynapseError.
  587. We might also raise an InvalidResponseError if the response from the remote
  588. server is just bogus.
  589. TODO: make this more useful to distinguish failures of the remote
  590. server from invalid events (there is probably no point in trying to
  591. re-fetch invalid events from every other HS in the room.)
  592. """
  593. if self._is_mine_server_name(dest):
  594. raise SynapseError(400, "Can't backfill from self.")
  595. events = await self._federation_client.backfill(
  596. dest, room_id, limit=limit, extremities=extremities
  597. )
  598. if not events:
  599. return
  600. with backfill_processing_after_timer.time():
  601. # if there are any events in the wrong room, the remote server is buggy and
  602. # should not be trusted.
  603. for ev in events:
  604. if ev.room_id != room_id:
  605. raise InvalidResponseError(
  606. f"Remote server {dest} returned event {ev.event_id} which is in "
  607. f"room {ev.room_id}, when we were backfilling in {room_id}"
  608. )
  609. await self._process_pulled_events(
  610. dest,
  611. events,
  612. backfilled=True,
  613. )
  614. @trace
  615. async def _get_missing_events_for_pdu(
  616. self, origin: str, pdu: EventBase, prevs: Set[str], min_depth: int
  617. ) -> None:
  618. """
  619. Args:
  620. origin: Origin of the pdu. Will be called to get the missing events
  621. pdu: received pdu
  622. prevs: List of event ids which we are missing
  623. min_depth: Minimum depth of events to return.
  624. """
  625. room_id = pdu.room_id
  626. event_id = pdu.event_id
  627. seen = await self._store.have_events_in_timeline(prevs)
  628. if not prevs - seen:
  629. return
  630. latest_frozen = await self._store.get_latest_event_ids_in_room(room_id)
  631. # We add the prev events that we have seen to the latest
  632. # list to ensure the remote server doesn't give them to us
  633. latest = seen | latest_frozen
  634. logger.info(
  635. "Requesting missing events between %s and %s",
  636. shortstr(latest),
  637. event_id,
  638. )
  639. # XXX: we set timeout to 10s to help workaround
  640. # https://github.com/matrix-org/synapse/issues/1733.
  641. # The reason is to avoid holding the linearizer lock
  642. # whilst processing inbound /send transactions, causing
  643. # FDs to stack up and block other inbound transactions
  644. # which empirically can currently take up to 30 minutes.
  645. #
  646. # N.B. this explicitly disables retry attempts.
  647. #
  648. # N.B. this also increases our chances of falling back to
  649. # fetching fresh state for the room if the missing event
  650. # can't be found, which slightly reduces our security.
  651. # it may also increase our DAG extremity count for the room,
  652. # causing additional state resolution? See https://github.com/matrix-org/synapse/issues/1760.
  653. # However, fetching state doesn't hold the linearizer lock
  654. # apparently.
  655. #
  656. # see https://github.com/matrix-org/synapse/pull/1744
  657. #
  658. # ----
  659. #
  660. # Update richvdh 2018/09/18: There are a number of problems with timing this
  661. # request out aggressively on the client side:
  662. #
  663. # - it plays badly with the server-side rate-limiter, which starts tarpitting you
  664. # if you send too many requests at once, so you end up with the server carefully
  665. # working through the backlog of your requests, which you have already timed
  666. # out.
  667. #
  668. # - for this request in particular, we now (as of
  669. # https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the
  670. # server can't produce a plausible-looking set of prev_events - so we becone
  671. # much more likely to reject the event.
  672. #
  673. # - contrary to what it says above, we do *not* fall back to fetching fresh state
  674. # for the room if get_missing_events times out. Rather, we give up processing
  675. # the PDU whose prevs we are missing, which then makes it much more likely that
  676. # we'll end up back here for the *next* PDU in the list, which exacerbates the
  677. # problem.
  678. #
  679. # - the aggressive 10s timeout was introduced to deal with incoming federation
  680. # requests taking 8 hours to process. It's not entirely clear why that was going
  681. # on; certainly there were other issues causing traffic storms which are now
  682. # resolved, and I think in any case we may be more sensible about our locking
  683. # now. We're *certainly* more sensible about our logging.
  684. #
  685. # All that said: Let's try increasing the timeout to 60s and see what happens.
  686. try:
  687. missing_events = await self._federation_client.get_missing_events(
  688. origin,
  689. room_id,
  690. earliest_events_ids=list(latest),
  691. latest_events=[pdu],
  692. limit=10,
  693. min_depth=min_depth,
  694. timeout=60000,
  695. )
  696. except (RequestSendFailed, HttpResponseException, NotRetryingDestination) as e:
  697. # We failed to get the missing events, but since we need to handle
  698. # the case of `get_missing_events` not returning the necessary
  699. # events anyway, it is safe to simply log the error and continue.
  700. logger.warning("Failed to get prev_events: %s", e)
  701. return
  702. logger.info("Got %d prev_events", len(missing_events))
  703. await self._process_pulled_events(origin, missing_events, backfilled=False)
  704. @trace
  705. async def _process_pulled_events(
  706. self, origin: str, events: Collection[EventBase], backfilled: bool
  707. ) -> None:
  708. """Process a batch of events we have pulled from a remote server
  709. Pulls in any events required to auth the events, persists the received events,
  710. and notifies clients, if appropriate.
  711. Assumes the events have already had their signatures and hashes checked.
  712. Params:
  713. origin: The server we received these events from
  714. events: The received events.
  715. backfilled: True if this is part of a historical batch of events (inhibits
  716. notification to clients, and validation of device keys.)
  717. """
  718. set_tag(
  719. SynapseTags.FUNC_ARG_PREFIX + "event_ids",
  720. str([event.event_id for event in events]),
  721. )
  722. set_tag(
  723. SynapseTags.FUNC_ARG_PREFIX + "event_ids.length",
  724. str(len(events)),
  725. )
  726. set_tag(SynapseTags.FUNC_ARG_PREFIX + "backfilled", str(backfilled))
  727. logger.debug(
  728. "processing pulled backfilled=%s events=%s",
  729. backfilled,
  730. [
  731. "event_id=%s,depth=%d,body=%s,prevs=%s\n"
  732. % (
  733. event.event_id,
  734. event.depth,
  735. event.content.get("body", event.type),
  736. event.prev_event_ids(),
  737. )
  738. for event in events
  739. ],
  740. )
  741. # Check if we already any of these have these events.
  742. # Note: we currently make a lookup in the database directly here rather than
  743. # checking the event cache, due to:
  744. # https://github.com/matrix-org/synapse/issues/13476
  745. existing_events_map = await self._store._get_events_from_db(
  746. [event.event_id for event in events]
  747. )
  748. new_events: List[EventBase] = []
  749. for event in events:
  750. event_id = event.event_id
  751. # If we've already seen this event ID...
  752. if event_id in existing_events_map:
  753. existing_event = existing_events_map[event_id]
  754. # ...and the event itself was not previously stored as an outlier...
  755. if not existing_event.event.internal_metadata.is_outlier():
  756. # ...then there's no need to persist it. We have it already.
  757. logger.info(
  758. "_process_pulled_event: Ignoring received event %s which we "
  759. "have already seen",
  760. event.event_id,
  761. )
  762. continue
  763. # While we have seen this event before, it was stored as an outlier.
  764. # We'll now persist it as a non-outlier.
  765. logger.info("De-outliering event %s", event_id)
  766. # Continue on with the events that are new to us.
  767. new_events.append(event)
  768. set_tag(
  769. SynapseTags.RESULT_PREFIX + "new_events.length",
  770. str(len(new_events)),
  771. )
  772. @trace
  773. async def _process_new_pulled_events(new_events: Collection[EventBase]) -> None:
  774. # We want to sort these by depth so we process them and tell clients about
  775. # them in order. It's also more efficient to backfill this way (`depth`
  776. # ascending) because one backfill event is likely to be the `prev_event` of
  777. # the next event we're going to process.
  778. sorted_events = sorted(new_events, key=lambda x: x.depth)
  779. for ev in sorted_events:
  780. with nested_logging_context(ev.event_id):
  781. await self._process_pulled_event(origin, ev, backfilled=backfilled)
  782. # Check if we've already tried to process these events at some point in the
  783. # past. We aren't concerned with the expontntial backoff here, just whether it
  784. # has failed to be processed before.
  785. event_ids_with_failed_pull_attempts = (
  786. await self._store.get_event_ids_with_failed_pull_attempts(
  787. [event.event_id for event in new_events]
  788. )
  789. )
  790. events_with_failed_pull_attempts, fresh_events = partition(
  791. new_events, lambda e: e.event_id in event_ids_with_failed_pull_attempts
  792. )
  793. set_tag(
  794. SynapseTags.FUNC_ARG_PREFIX + "events_with_failed_pull_attempts",
  795. str(event_ids_with_failed_pull_attempts),
  796. )
  797. set_tag(
  798. SynapseTags.RESULT_PREFIX + "events_with_failed_pull_attempts.length",
  799. str(len(events_with_failed_pull_attempts)),
  800. )
  801. set_tag(
  802. SynapseTags.FUNC_ARG_PREFIX + "fresh_events",
  803. str([event.event_id for event in fresh_events]),
  804. )
  805. set_tag(
  806. SynapseTags.RESULT_PREFIX + "fresh_events.length",
  807. str(len(fresh_events)),
  808. )
  809. # Process previously failed backfill events in the background to not waste
  810. # time on something that is likely to fail again.
  811. if len(events_with_failed_pull_attempts) > 0:
  812. run_as_background_process(
  813. "_process_new_pulled_events_with_failed_pull_attempts",
  814. _process_new_pulled_events,
  815. events_with_failed_pull_attempts,
  816. )
  817. # We can optimistically try to process and wait for the event to be fully
  818. # persisted if we've never tried before.
  819. if len(fresh_events) > 0:
  820. await _process_new_pulled_events(fresh_events)
  821. @trace
  822. @tag_args
  823. async def _process_pulled_event(
  824. self, origin: str, event: EventBase, backfilled: bool
  825. ) -> None:
  826. """Process a single event that we have pulled from a remote server
  827. Pulls in any events required to auth the event, persists the received event,
  828. and notifies clients, if appropriate.
  829. Assumes the event has already had its signatures and hashes checked.
  830. This is somewhat equivalent to on_receive_pdu, but applies somewhat different
  831. logic in the case that we are missing prev_events (in particular, it just
  832. requests the state at that point, rather than triggering a get_missing_events) -
  833. so is appropriate when we have pulled the event from a remote server, rather
  834. than having it pushed to us.
  835. Params:
  836. origin: The server we received this event from
  837. events: The received event
  838. backfilled: True if this is part of a historical batch of events (inhibits
  839. notification to clients, and validation of device keys.)
  840. """
  841. logger.info("Processing pulled event %s", event)
  842. # This function should not be used to persist outliers (use something
  843. # else) because this does a bunch of operations that aren't necessary
  844. # (extra work; in particular, it makes sure we have all the prev_events
  845. # and resolves the state across those prev events). If you happen to run
  846. # into a situation where the event you're trying to process/backfill is
  847. # marked as an `outlier`, then you should update that spot to return an
  848. # `EventBase` copy that doesn't have `outlier` flag set.
  849. #
  850. # `EventBase` is used to represent both an event we have not yet
  851. # persisted, and one that we have persisted and now keep in the cache.
  852. # In an ideal world this method would only be called with the first type
  853. # of event, but it turns out that's not actually the case and for
  854. # example, you could get an event from cache that is marked as an
  855. # `outlier` (fix up that spot though).
  856. assert not event.internal_metadata.is_outlier(), (
  857. "Outlier event passed to _process_pulled_event. "
  858. "To persist an event as a non-outlier, make sure to pass in a copy without `event.internal_metadata.outlier = true`."
  859. )
  860. event_id = event.event_id
  861. try:
  862. self._sanity_check_event(event)
  863. except SynapseError as err:
  864. logger.warning("Event %s failed sanity check: %s", event_id, err)
  865. await self._store.record_event_failed_pull_attempt(
  866. event.room_id, event_id, str(err)
  867. )
  868. return
  869. try:
  870. try:
  871. context = await self._compute_event_context_with_maybe_missing_prevs(
  872. origin, event
  873. )
  874. await self._process_received_pdu(
  875. origin,
  876. event,
  877. context,
  878. backfilled=backfilled,
  879. )
  880. except PartialStateConflictError:
  881. # The room was un-partial stated while we were processing the event.
  882. # Try once more, with full state this time.
  883. context = await self._compute_event_context_with_maybe_missing_prevs(
  884. origin, event
  885. )
  886. # We ought to have full state now, barring some unlikely race where we left and
  887. # rejoned the room in the background.
  888. if context.partial_state:
  889. raise AssertionError(
  890. f"Event {event.event_id} still has a partial resolved state "
  891. f"after room {event.room_id} was un-partial stated"
  892. )
  893. await self._process_received_pdu(
  894. origin,
  895. event,
  896. context,
  897. backfilled=backfilled,
  898. )
  899. except FederationPullAttemptBackoffError as exc:
  900. # Log a warning about why we failed to process the event (the error message
  901. # for `FederationPullAttemptBackoffError` is pretty good)
  902. logger.warning("_process_pulled_event: %s", exc)
  903. # We do not record a failed pull attempt when we backoff fetching a missing
  904. # `prev_event` because not being able to fetch the `prev_events` just means
  905. # we won't be able to de-outlier the pulled event. But we can still use an
  906. # `outlier` in the state/auth chain for another event. So we shouldn't stop
  907. # a downstream event from trying to pull it.
  908. #
  909. # This avoids a cascade of backoff for all events in the DAG downstream from
  910. # one event backoff upstream.
  911. except FederationError as e:
  912. await self._store.record_event_failed_pull_attempt(
  913. event.room_id, event_id, str(e)
  914. )
  915. if e.code == 403:
  916. logger.warning("Pulled event %s failed history check.", event_id)
  917. else:
  918. raise
  919. @trace
  920. async def _compute_event_context_with_maybe_missing_prevs(
  921. self, dest: str, event: EventBase
  922. ) -> EventContext:
  923. """Build an EventContext structure for a non-outlier event whose prev_events may
  924. be missing.
  925. This is used when we have pulled a batch of events from a remote server, and may
  926. not have all the prev_events.
  927. To build an EventContext, we need to calculate the state before the event. If we
  928. already have all the prev_events for `event`, we can simply use the state after
  929. the prev_events to calculate the state before `event`.
  930. Otherwise, the missing prevs become new backwards extremities, and we fall back
  931. to asking the remote server for the state after each missing `prev_event`,
  932. and resolving across them.
  933. That's ok provided we then resolve the state against other bits of the DAG
  934. before using it - in other words, that the received event `event` is not going
  935. to become the only forwards_extremity in the room (which will ensure that you
  936. can't just take over a room by sending an event, withholding its prev_events,
  937. and declaring yourself to be an admin in the subsequent state request).
  938. In other words: we should only call this method if `event` has been *pulled*
  939. as part of a batch of missing prev events, or similar.
  940. Params:
  941. dest: the remote server to ask for state at the missing prevs. Typically,
  942. this will be the server we got `event` from.
  943. event: an event to check for missing prevs.
  944. Returns:
  945. The event context.
  946. Raises:
  947. FederationPullAttemptBackoffError if we are are deliberately not attempting
  948. to pull one of the given event's `prev_event`s over federation because
  949. we've already done so recently and are backing off.
  950. FederationError if we fail to get the state from the remote server after any
  951. missing `prev_event`s.
  952. """
  953. room_id = event.room_id
  954. event_id = event.event_id
  955. prevs = set(event.prev_event_ids())
  956. seen = await self._store.have_events_in_timeline(prevs)
  957. missing_prevs = prevs - seen
  958. # If we've already recently attempted to pull this missing event, don't
  959. # try it again so soon. Since we have to fetch all of the prev_events, we can
  960. # bail early here if we find any to ignore.
  961. prevs_with_pull_backoff = (
  962. await self._store.get_event_ids_to_not_pull_from_backoff(
  963. room_id, missing_prevs
  964. )
  965. )
  966. if len(prevs_with_pull_backoff) > 0:
  967. raise FederationPullAttemptBackoffError(
  968. event_ids=prevs_with_pull_backoff.keys(),
  969. message=(
  970. f"While computing context for event={event_id}, not attempting to "
  971. f"pull missing prev_events={list(prevs_with_pull_backoff.keys())} "
  972. "because we already tried to pull recently (backing off)."
  973. ),
  974. retry_after_ms=(
  975. max(prevs_with_pull_backoff.values()) - self._clock.time_msec()
  976. ),
  977. )
  978. if not missing_prevs:
  979. return await self._state_handler.compute_event_context(event)
  980. logger.info(
  981. "Event %s is missing prev_events %s: calculating state for a "
  982. "backwards extremity",
  983. event_id,
  984. shortstr(missing_prevs),
  985. )
  986. # Calculate the state after each of the previous events, and
  987. # resolve them to find the correct state at the current event.
  988. try:
  989. # Determine whether we may be about to retrieve partial state
  990. # Events may be un-partial stated right after we compute the partial state
  991. # flag, but that's okay, as long as the flag errs on the conservative side.
  992. partial_state_flags = await self._store.get_partial_state_events(seen)
  993. partial_state = any(partial_state_flags.values())
  994. # Get the state of the events we know about
  995. ours = await self._state_storage_controller.get_state_groups_ids(
  996. room_id, seen, await_full_state=False
  997. )
  998. # state_maps is a list of mappings from (type, state_key) to event_id
  999. state_maps: List[StateMap[str]] = list(ours.values())
  1000. # we don't need this any more, let's delete it.
  1001. del ours
  1002. # Ask the remote server for the states we don't
  1003. # know about
  1004. for p in missing_prevs:
  1005. logger.info("Requesting state after missing prev_event %s", p)
  1006. with nested_logging_context(p):
  1007. # note that if any of the missing prevs share missing state or
  1008. # auth events, the requests to fetch those events are deduped
  1009. # by the get_pdu_cache in federation_client.
  1010. remote_state_map = (
  1011. await self._get_state_ids_after_missing_prev_event(
  1012. dest, room_id, p
  1013. )
  1014. )
  1015. state_maps.append(remote_state_map)
  1016. room_version = await self._store.get_room_version_id(room_id)
  1017. state_map = await self._state_resolution_handler.resolve_events_with_store(
  1018. room_id,
  1019. room_version,
  1020. state_maps,
  1021. event_map={event_id: event},
  1022. state_res_store=StateResolutionStore(self._store),
  1023. )
  1024. except Exception as e:
  1025. logger.warning(
  1026. "Error attempting to resolve state at missing prev_events: %s", e
  1027. )
  1028. raise FederationError(
  1029. "ERROR",
  1030. 403,
  1031. "We can't get valid state history.",
  1032. affected=event_id,
  1033. )
  1034. return await self._state_handler.compute_event_context(
  1035. event, state_ids_before_event=state_map, partial_state=partial_state
  1036. )
  1037. @trace
  1038. @tag_args
  1039. async def _get_state_ids_after_missing_prev_event(
  1040. self,
  1041. destination: str,
  1042. room_id: str,
  1043. event_id: str,
  1044. ) -> StateMap[str]:
  1045. """Requests all of the room state at a given event from a remote homeserver.
  1046. Args:
  1047. destination: The remote homeserver to query for the state.
  1048. room_id: The id of the room we're interested in.
  1049. event_id: The id of the event we want the state at.
  1050. Returns:
  1051. The event ids of the state *after* the given event.
  1052. Raises:
  1053. InvalidResponseError: if the remote homeserver's response contains fields
  1054. of the wrong type.
  1055. """
  1056. # It would be better if we could query the difference from our known
  1057. # state to the given `event_id` so the sending server doesn't have to
  1058. # send as much and we don't have to process as many events. For example
  1059. # in a room like #matrix:matrix.org, we get 200k events (77k state_events, 122k
  1060. # auth_events) from this call.
  1061. #
  1062. # Tracked by https://github.com/matrix-org/synapse/issues/13618
  1063. (
  1064. state_event_ids,
  1065. auth_event_ids,
  1066. ) = await self._federation_client.get_room_state_ids(
  1067. destination, room_id, event_id=event_id
  1068. )
  1069. logger.debug(
  1070. "state_ids returned %i state events, %i auth events",
  1071. len(state_event_ids),
  1072. len(auth_event_ids),
  1073. )
  1074. # Start by checking events we already have in the DB
  1075. desired_events = set(state_event_ids)
  1076. desired_events.add(event_id)
  1077. logger.debug("Fetching %i events from cache/store", len(desired_events))
  1078. have_events = await self._store.have_seen_events(room_id, desired_events)
  1079. missing_desired_event_ids = desired_events - have_events
  1080. logger.debug(
  1081. "We are missing %i events (got %i)",
  1082. len(missing_desired_event_ids),
  1083. len(have_events),
  1084. )
  1085. # We probably won't need most of the auth events, so let's just check which
  1086. # we have for now, rather than thrashing the event cache with them all
  1087. # unnecessarily.
  1088. # TODO: we probably won't actually need all of the auth events, since we
  1089. # already have a bunch of the state events. It would be nice if the
  1090. # federation api gave us a way of finding out which we actually need.
  1091. missing_auth_event_ids = set(auth_event_ids) - have_events
  1092. missing_auth_event_ids.difference_update(
  1093. await self._store.have_seen_events(room_id, missing_auth_event_ids)
  1094. )
  1095. logger.debug("We are also missing %i auth events", len(missing_auth_event_ids))
  1096. missing_event_ids = missing_desired_event_ids | missing_auth_event_ids
  1097. set_tag(
  1098. SynapseTags.RESULT_PREFIX + "missing_auth_event_ids",
  1099. str(missing_auth_event_ids),
  1100. )
  1101. set_tag(
  1102. SynapseTags.RESULT_PREFIX + "missing_auth_event_ids.length",
  1103. str(len(missing_auth_event_ids)),
  1104. )
  1105. set_tag(
  1106. SynapseTags.RESULT_PREFIX + "missing_desired_event_ids",
  1107. str(missing_desired_event_ids),
  1108. )
  1109. set_tag(
  1110. SynapseTags.RESULT_PREFIX + "missing_desired_event_ids.length",
  1111. str(len(missing_desired_event_ids)),
  1112. )
  1113. # Making an individual request for each of 1000s of events has a lot of
  1114. # overhead. On the other hand, we don't really want to fetch all of the events
  1115. # if we already have most of them.
  1116. #
  1117. # As an arbitrary heuristic, if we are missing more than 10% of the events, then
  1118. # we fetch the whole state.
  1119. #
  1120. # TODO: might it be better to have an API which lets us do an aggregate event
  1121. # request
  1122. if (len(missing_event_ids) * 10) >= len(auth_event_ids) + len(state_event_ids):
  1123. logger.debug("Requesting complete state from remote")
  1124. await self._get_state_and_persist(destination, room_id, event_id)
  1125. else:
  1126. logger.debug("Fetching %i events from remote", len(missing_event_ids))
  1127. await self._get_events_and_persist(
  1128. destination=destination, room_id=room_id, event_ids=missing_event_ids
  1129. )
  1130. # We now need to fill out the state map, which involves fetching the
  1131. # type and state key for each event ID in the state.
  1132. state_map = {}
  1133. event_metadata = await self._store.get_metadata_for_events(state_event_ids)
  1134. for state_event_id, metadata in event_metadata.items():
  1135. if metadata.room_id != room_id:
  1136. # This is a bogus situation, but since we may only discover it a long time
  1137. # after it happened, we try our best to carry on, by just omitting the
  1138. # bad events from the returned state set.
  1139. #
  1140. # This can happen if a remote server claims that the state or
  1141. # auth_events at an event in room A are actually events in room B
  1142. logger.warning(
  1143. "Remote server %s claims event %s in room %s is an auth/state "
  1144. "event in room %s",
  1145. destination,
  1146. state_event_id,
  1147. metadata.room_id,
  1148. room_id,
  1149. )
  1150. continue
  1151. if metadata.state_key is None:
  1152. logger.warning(
  1153. "Remote server gave us non-state event in state: %s", state_event_id
  1154. )
  1155. continue
  1156. state_map[(metadata.event_type, metadata.state_key)] = state_event_id
  1157. # if we couldn't get the prev event in question, that's a problem.
  1158. remote_event = await self._store.get_event(
  1159. event_id,
  1160. allow_none=True,
  1161. allow_rejected=True,
  1162. redact_behaviour=EventRedactBehaviour.as_is,
  1163. )
  1164. if not remote_event:
  1165. raise Exception("Unable to get missing prev_event %s" % (event_id,))
  1166. # missing state at that event is a warning, not a blocker
  1167. # XXX: this doesn't sound right? it means that we'll end up with incomplete
  1168. # state.
  1169. failed_to_fetch = desired_events - event_metadata.keys()
  1170. # `event_id` could be missing from `event_metadata` because it's not necessarily
  1171. # a state event. We've already checked that we've fetched it above.
  1172. failed_to_fetch.discard(event_id)
  1173. if failed_to_fetch:
  1174. logger.warning(
  1175. "Failed to fetch missing state events for %s %s",
  1176. event_id,
  1177. failed_to_fetch,
  1178. )
  1179. set_tag(
  1180. SynapseTags.RESULT_PREFIX + "failed_to_fetch",
  1181. str(failed_to_fetch),
  1182. )
  1183. set_tag(
  1184. SynapseTags.RESULT_PREFIX + "failed_to_fetch.length",
  1185. str(len(failed_to_fetch)),
  1186. )
  1187. if remote_event.is_state() and remote_event.rejected_reason is None:
  1188. state_map[
  1189. (remote_event.type, remote_event.state_key)
  1190. ] = remote_event.event_id
  1191. return state_map
  1192. @trace
  1193. @tag_args
  1194. async def _get_state_and_persist(
  1195. self, destination: str, room_id: str, event_id: str
  1196. ) -> None:
  1197. """Get the complete room state at a given event, and persist any new events
  1198. as outliers"""
  1199. room_version = await self._store.get_room_version(room_id)
  1200. auth_events, state_events = await self._federation_client.get_room_state(
  1201. destination, room_id, event_id=event_id, room_version=room_version
  1202. )
  1203. logger.info("/state returned %i events", len(auth_events) + len(state_events))
  1204. await self._auth_and_persist_outliers(
  1205. room_id, itertools.chain(auth_events, state_events)
  1206. )
  1207. # we also need the event itself.
  1208. if not await self._store.have_seen_event(room_id, event_id):
  1209. await self._get_events_and_persist(
  1210. destination=destination, room_id=room_id, event_ids=(event_id,)
  1211. )
  1212. @trace
  1213. async def _process_received_pdu(
  1214. self,
  1215. origin: str,
  1216. event: EventBase,
  1217. context: EventContext,
  1218. backfilled: bool = False,
  1219. ) -> None:
  1220. """Called when we have a new non-outlier event.
  1221. This is called when we have a new event to add to the room DAG. This can be
  1222. due to:
  1223. * events received directly via a /send request
  1224. * events retrieved via get_missing_events after a /send request
  1225. * events backfilled after a client request.
  1226. It's not currently used for events received from incoming send_{join,knock,leave}
  1227. requests (which go via on_send_membership_event), nor for joins created by a
  1228. remote join dance (which go via process_remote_join).
  1229. We need to do auth checks and put it through the StateHandler.
  1230. Args:
  1231. origin: server sending the event
  1232. event: event to be persisted
  1233. context: The `EventContext` to persist the event with.
  1234. backfilled: True if this is part of a historical batch of events (inhibits
  1235. notification to clients, and validation of device keys.)
  1236. PartialStateConflictError: if the room was un-partial stated in between
  1237. computing the state at the event and persisting it. The caller should
  1238. recompute `context` and retry exactly once when this happens.
  1239. """
  1240. logger.debug("Processing event: %s", event)
  1241. assert not event.internal_metadata.outlier
  1242. try:
  1243. await self._check_event_auth(origin, event, context)
  1244. except AuthError as e:
  1245. # This happens only if we couldn't find the auth events. We'll already have
  1246. # logged a warning, so now we just convert to a FederationError.
  1247. raise FederationError("ERROR", e.code, e.msg, affected=event.event_id)
  1248. if not backfilled and not context.rejected:
  1249. # For new (non-backfilled and non-outlier) events we check if the event
  1250. # passes auth based on the current state. If it doesn't then we
  1251. # "soft-fail" the event.
  1252. await self._check_for_soft_fail(event, context=context, origin=origin)
  1253. await self._run_push_actions_and_persist_event(event, context, backfilled)
  1254. if backfilled or context.rejected:
  1255. return
  1256. await self._maybe_kick_guest_users(event)
  1257. # For encrypted messages we check that we know about the sending device,
  1258. # if we don't then we mark the device cache for that user as stale.
  1259. if event.type == EventTypes.Encrypted:
  1260. device_id = event.content.get("device_id")
  1261. sender_key = event.content.get("sender_key")
  1262. cached_devices = await self._store.get_cached_devices_for_user(event.sender)
  1263. resync = False # Whether we should resync device lists.
  1264. device = None
  1265. if device_id is not None:
  1266. device = cached_devices.get(device_id)
  1267. if device is None:
  1268. logger.info(
  1269. "Received event from remote device not in our cache: %s %s",
  1270. event.sender,
  1271. device_id,
  1272. )
  1273. resync = True
  1274. # We also check if the `sender_key` matches what we expect.
  1275. if sender_key is not None:
  1276. # Figure out what sender key we're expecting. If we know the
  1277. # device and recognize the algorithm then we can work out the
  1278. # exact key to expect. Otherwise check it matches any key we
  1279. # have for that device.
  1280. current_keys: Container[str] = []
  1281. if device:
  1282. keys = device.get("keys", {}).get("keys", {})
  1283. if (
  1284. event.content.get("algorithm")
  1285. == RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2
  1286. ):
  1287. # For this algorithm we expect a curve25519 key.
  1288. key_name = "curve25519:%s" % (device_id,)
  1289. current_keys = [keys.get(key_name)]
  1290. else:
  1291. # We don't know understand the algorithm, so we just
  1292. # check it matches a key for the device.
  1293. current_keys = keys.values()
  1294. elif device_id:
  1295. # We don't have any keys for the device ID.
  1296. pass
  1297. else:
  1298. # The event didn't include a device ID, so we just look for
  1299. # keys across all devices.
  1300. current_keys = [
  1301. key
  1302. for device in cached_devices.values()
  1303. for key in device.get("keys", {}).get("keys", {}).values()
  1304. ]
  1305. # We now check that the sender key matches (one of) the expected
  1306. # keys.
  1307. if sender_key not in current_keys:
  1308. logger.info(
  1309. "Received event from remote device with unexpected sender key: %s %s: %s",
  1310. event.sender,
  1311. device_id or "<no device_id>",
  1312. sender_key,
  1313. )
  1314. resync = True
  1315. if resync:
  1316. run_as_background_process(
  1317. "resync_device_due_to_pdu",
  1318. self._resync_device,
  1319. event.sender,
  1320. )
  1321. async def _resync_device(self, sender: str) -> None:
  1322. """We have detected that the device list for the given user may be out
  1323. of sync, so we try and resync them.
  1324. """
  1325. try:
  1326. await self._store.mark_remote_users_device_caches_as_stale((sender,))
  1327. # Immediately attempt a resync in the background
  1328. if self._config.worker.worker_app:
  1329. await self._multi_user_device_resync(user_ids=[sender])
  1330. else:
  1331. await self._device_list_updater.multi_user_device_resync(
  1332. user_ids=[sender]
  1333. )
  1334. except Exception:
  1335. logger.exception("Failed to resync device for %s", sender)
  1336. async def backfill_event_id(
  1337. self, destinations: StrCollection, room_id: str, event_id: str
  1338. ) -> PulledPduInfo:
  1339. """Backfill a single event and persist it as a non-outlier which means
  1340. we also pull in all of the state and auth events necessary for it.
  1341. Args:
  1342. destination: The homeserver to pull the given event_id from.
  1343. room_id: The room where the event is from.
  1344. event_id: The event ID to backfill.
  1345. Raises:
  1346. FederationError if we are unable to find the event from the destination
  1347. """
  1348. logger.info("backfill_event_id: event_id=%s", event_id)
  1349. room_version = await self._store.get_room_version(room_id)
  1350. pulled_pdu_info = await self._federation_client.get_pdu(
  1351. destinations,
  1352. event_id,
  1353. room_version,
  1354. )
  1355. if not pulled_pdu_info:
  1356. raise FederationError(
  1357. "ERROR",
  1358. 404,
  1359. f"Unable to find event_id={event_id} from remote servers to backfill.",
  1360. affected=event_id,
  1361. )
  1362. # Persist the event we just fetched, including pulling all of the state
  1363. # and auth events to de-outlier it. This also sets up the necessary
  1364. # `state_groups` for the event.
  1365. await self._process_pulled_events(
  1366. pulled_pdu_info.pull_origin,
  1367. [pulled_pdu_info.pdu],
  1368. # Prevent notifications going to clients
  1369. backfilled=True,
  1370. )
  1371. return pulled_pdu_info
  1372. @trace
  1373. @tag_args
  1374. async def _get_events_and_persist(
  1375. self, destination: str, room_id: str, event_ids: StrCollection
  1376. ) -> None:
  1377. """Fetch the given events from a server, and persist them as outliers.
  1378. This function *does not* recursively get missing auth events of the
  1379. newly fetched events. Callers must include in the `event_ids` argument
  1380. any missing events from the auth chain.
  1381. Logs a warning if we can't find the given event.
  1382. """
  1383. room_version = await self._store.get_room_version(room_id)
  1384. events: List[EventBase] = []
  1385. async def get_event(event_id: str) -> None:
  1386. with nested_logging_context(event_id):
  1387. try:
  1388. pulled_pdu_info = await self._federation_client.get_pdu(
  1389. [destination],
  1390. event_id,
  1391. room_version,
  1392. )
  1393. if pulled_pdu_info is None:
  1394. logger.warning(
  1395. "Server %s didn't return event %s",
  1396. destination,
  1397. event_id,
  1398. )
  1399. return
  1400. events.append(pulled_pdu_info.pdu)
  1401. except Exception as e:
  1402. logger.warning(
  1403. "Error fetching missing state/auth event %s: %s %s",
  1404. event_id,
  1405. type(e),
  1406. e,
  1407. )
  1408. await concurrently_execute(get_event, event_ids, 5)
  1409. logger.info("Fetched %i events of %i requested", len(events), len(event_ids))
  1410. await self._auth_and_persist_outliers(room_id, events)
  1411. @trace
  1412. async def _auth_and_persist_outliers(
  1413. self, room_id: str, events: Iterable[EventBase]
  1414. ) -> None:
  1415. """Persist a batch of outlier events fetched from remote servers.
  1416. We first sort the events to make sure that we process each event's auth_events
  1417. before the event itself.
  1418. We then mark the events as outliers, persist them to the database, and, where
  1419. appropriate (eg, an invite), awake the notifier.
  1420. Params:
  1421. room_id: the room that the events are meant to be in (though this has
  1422. not yet been checked)
  1423. events: the events that have been fetched
  1424. """
  1425. event_map = {event.event_id: event for event in events}
  1426. event_ids = event_map.keys()
  1427. set_tag(
  1428. SynapseTags.FUNC_ARG_PREFIX + "event_ids",
  1429. str(event_ids),
  1430. )
  1431. set_tag(
  1432. SynapseTags.FUNC_ARG_PREFIX + "event_ids.length",
  1433. str(len(event_ids)),
  1434. )
  1435. # filter out any events we have already seen. This might happen because
  1436. # the events were eagerly pushed to us (eg, during a room join), or because
  1437. # another thread has raced against us since we decided to request the event.
  1438. #
  1439. # This is just an optimisation, so it doesn't need to be watertight - the event
  1440. # persister does another round of deduplication.
  1441. seen_remotes = await self._store.have_seen_events(room_id, event_map.keys())
  1442. for s in seen_remotes:
  1443. event_map.pop(s, None)
  1444. # XXX: it might be possible to kick this process off in parallel with fetching
  1445. # the events.
  1446. while event_map:
  1447. # build a list of events whose auth events are not in the queue.
  1448. roots = tuple(
  1449. ev
  1450. for ev in event_map.values()
  1451. if not any(aid in event_map for aid in ev.auth_event_ids())
  1452. )
  1453. if not roots:
  1454. # if *none* of the remaining events are ready, that means
  1455. # we have a loop. This either means a bug in our logic, or that
  1456. # somebody has managed to create a loop (which requires finding a
  1457. # hash collision in room v2 and later).
  1458. logger.warning(
  1459. "Loop found in auth events while fetching missing state/auth "
  1460. "events: %s",
  1461. shortstr(event_map.keys()),
  1462. )
  1463. return
  1464. logger.info(
  1465. "Persisting %i of %i remaining outliers: %s",
  1466. len(roots),
  1467. len(event_map),
  1468. shortstr(e.event_id for e in roots),
  1469. )
  1470. await self._auth_and_persist_outliers_inner(room_id, roots)
  1471. for ev in roots:
  1472. del event_map[ev.event_id]
  1473. async def _auth_and_persist_outliers_inner(
  1474. self, room_id: str, fetched_events: Collection[EventBase]
  1475. ) -> None:
  1476. """Helper for _auth_and_persist_outliers
  1477. Persists a batch of events where we have (theoretically) already persisted all
  1478. of their auth events.
  1479. Marks the events as outliers, auths them, persists them to the database, and,
  1480. where appropriate (eg, an invite), awakes the notifier.
  1481. Params:
  1482. origin: where the events came from
  1483. room_id: the room that the events are meant to be in (though this has
  1484. not yet been checked)
  1485. fetched_events: the events to persist
  1486. """
  1487. # get all the auth events for all the events in this batch. By now, they should
  1488. # have been persisted.
  1489. auth_events = {
  1490. aid for event in fetched_events for aid in event.auth_event_ids()
  1491. }
  1492. persisted_events = await self._store.get_events(
  1493. auth_events,
  1494. allow_rejected=True,
  1495. )
  1496. events_and_contexts_to_persist: List[Tuple[EventBase, EventContext]] = []
  1497. async def prep(event: EventBase) -> None:
  1498. with nested_logging_context(suffix=event.event_id):
  1499. auth = []
  1500. for auth_event_id in event.auth_event_ids():
  1501. ae = persisted_events.get(auth_event_id)
  1502. if not ae:
  1503. # the fact we can't find the auth event doesn't mean it doesn't
  1504. # exist, which means it is premature to reject `event`. Instead we
  1505. # just ignore it for now.
  1506. logger.warning(
  1507. "Dropping event %s, which relies on auth_event %s, which could not be found",
  1508. event,
  1509. auth_event_id,
  1510. )
  1511. return
  1512. auth.append(ae)
  1513. # we're not bothering about room state, so flag the event as an outlier.
  1514. event.internal_metadata.outlier = True
  1515. context = EventContext.for_outlier(self._storage_controllers)
  1516. try:
  1517. validate_event_for_room_version(event)
  1518. await check_state_independent_auth_rules(self._store, event)
  1519. check_state_dependent_auth_rules(event, auth)
  1520. except AuthError as e:
  1521. logger.warning("Rejecting %r because %s", event, e)
  1522. context.rejected = RejectedReason.AUTH_ERROR
  1523. except EventSizeError as e:
  1524. if e.unpersistable:
  1525. # This event is completely unpersistable.
  1526. raise e
  1527. # Otherwise, we are somewhat lenient and just persist the event
  1528. # as rejected, for moderate compatibility with older Synapse
  1529. # versions.
  1530. logger.warning("While validating received event %r: %s", event, e)
  1531. context.rejected = RejectedReason.OVERSIZED_EVENT
  1532. events_and_contexts_to_persist.append((event, context))
  1533. for event in fetched_events:
  1534. await prep(event)
  1535. await self.persist_events_and_notify(
  1536. room_id,
  1537. events_and_contexts_to_persist,
  1538. # Mark these events backfilled as they're historic events that will
  1539. # eventually be backfilled. For example, missing events we fetch
  1540. # during backfill should be marked as backfilled as well.
  1541. backfilled=True,
  1542. )
  1543. @trace
  1544. async def _check_event_auth(
  1545. self, origin: Optional[str], event: EventBase, context: EventContext
  1546. ) -> None:
  1547. """
  1548. Checks whether an event should be rejected (for failing auth checks).
  1549. Args:
  1550. origin: The host the event originates from. This is used to fetch
  1551. any missing auth events. It can be set to None, but only if we are
  1552. sure that we already have all the auth events.
  1553. event: The event itself.
  1554. context:
  1555. The event context.
  1556. Raises:
  1557. AuthError if we were unable to find copies of the event's auth events.
  1558. (Most other failures just cause us to set `context.rejected`.)
  1559. """
  1560. # This method should only be used for non-outliers
  1561. assert not event.internal_metadata.outlier
  1562. # first of all, check that the event itself is valid.
  1563. try:
  1564. validate_event_for_room_version(event)
  1565. except AuthError as e:
  1566. logger.warning("While validating received event %r: %s", event, e)
  1567. # TODO: use a different rejected reason here?
  1568. context.rejected = RejectedReason.AUTH_ERROR
  1569. return
  1570. except EventSizeError as e:
  1571. if e.unpersistable:
  1572. # This event is completely unpersistable.
  1573. raise e
  1574. # Otherwise, we are somewhat lenient and just persist the event
  1575. # as rejected, for moderate compatibility with older Synapse
  1576. # versions.
  1577. logger.warning("While validating received event %r: %s", event, e)
  1578. context.rejected = RejectedReason.OVERSIZED_EVENT
  1579. return
  1580. # next, check that we have all of the event's auth events.
  1581. #
  1582. # Note that this can raise AuthError, which we want to propagate to the
  1583. # caller rather than swallow with `context.rejected` (since we cannot be
  1584. # certain that there is a permanent problem with the event).
  1585. claimed_auth_events = await self._load_or_fetch_auth_events_for_event(
  1586. origin, event
  1587. )
  1588. set_tag(
  1589. SynapseTags.RESULT_PREFIX + "claimed_auth_events",
  1590. str([ev.event_id for ev in claimed_auth_events]),
  1591. )
  1592. set_tag(
  1593. SynapseTags.RESULT_PREFIX + "claimed_auth_events.length",
  1594. str(len(claimed_auth_events)),
  1595. )
  1596. # ... and check that the event passes auth at those auth events.
  1597. # https://spec.matrix.org/v1.3/server-server-api/#checks-performed-on-receipt-of-a-pdu:
  1598. # 4. Passes authorization rules based on the event’s auth events,
  1599. # otherwise it is rejected.
  1600. try:
  1601. await check_state_independent_auth_rules(self._store, event)
  1602. check_state_dependent_auth_rules(event, claimed_auth_events)
  1603. except AuthError as e:
  1604. logger.warning(
  1605. "While checking auth of %r against auth_events: %s", event, e
  1606. )
  1607. context.rejected = RejectedReason.AUTH_ERROR
  1608. return
  1609. # now check the auth rules pass against the room state before the event
  1610. # https://spec.matrix.org/v1.3/server-server-api/#checks-performed-on-receipt-of-a-pdu:
  1611. # 5. Passes authorization rules based on the state before the event,
  1612. # otherwise it is rejected.
  1613. #
  1614. # ... however, if we only have partial state for the room, then there is a good
  1615. # chance that we'll be missing some of the state needed to auth the new event.
  1616. # So, we state-resolve the auth events that we are given against the state that
  1617. # we know about, which ensures things like bans are applied. (Note that we'll
  1618. # already have checked we have all the auth events, in
  1619. # _load_or_fetch_auth_events_for_event above)
  1620. if context.partial_state:
  1621. room_version = await self._store.get_room_version_id(event.room_id)
  1622. local_state_id_map = await context.get_prev_state_ids()
  1623. claimed_auth_events_id_map = {
  1624. (ev.type, ev.state_key): ev.event_id for ev in claimed_auth_events
  1625. }
  1626. state_for_auth_id_map = (
  1627. await self._state_resolution_handler.resolve_events_with_store(
  1628. event.room_id,
  1629. room_version,
  1630. [local_state_id_map, claimed_auth_events_id_map],
  1631. event_map=None,
  1632. state_res_store=StateResolutionStore(self._store),
  1633. )
  1634. )
  1635. else:
  1636. event_types = event_auth.auth_types_for_event(event.room_version, event)
  1637. state_for_auth_id_map = await context.get_prev_state_ids(
  1638. StateFilter.from_types(event_types)
  1639. )
  1640. calculated_auth_event_ids = self._event_auth_handler.compute_auth_events(
  1641. event, state_for_auth_id_map, for_verification=True
  1642. )
  1643. # if those are the same, we're done here.
  1644. if collections.Counter(event.auth_event_ids()) == collections.Counter(
  1645. calculated_auth_event_ids
  1646. ):
  1647. return
  1648. # otherwise, re-run the auth checks based on what we calculated.
  1649. calculated_auth_events = await self._store.get_events_as_list(
  1650. calculated_auth_event_ids
  1651. )
  1652. # log the differences
  1653. claimed_auth_event_map = {(e.type, e.state_key): e for e in claimed_auth_events}
  1654. calculated_auth_event_map = {
  1655. (e.type, e.state_key): e for e in calculated_auth_events
  1656. }
  1657. logger.info(
  1658. "event's auth_events are different to our calculated auth_events. "
  1659. "Claimed but not calculated: %s. Calculated but not claimed: %s",
  1660. [
  1661. ev
  1662. for k, ev in claimed_auth_event_map.items()
  1663. if k not in calculated_auth_event_map
  1664. or calculated_auth_event_map[k].event_id != ev.event_id
  1665. ],
  1666. [
  1667. ev
  1668. for k, ev in calculated_auth_event_map.items()
  1669. if k not in claimed_auth_event_map
  1670. or claimed_auth_event_map[k].event_id != ev.event_id
  1671. ],
  1672. )
  1673. try:
  1674. check_state_dependent_auth_rules(event, calculated_auth_events)
  1675. except AuthError as e:
  1676. logger.warning(
  1677. "While checking auth of %r against room state before the event: %s",
  1678. event,
  1679. e,
  1680. )
  1681. context.rejected = RejectedReason.AUTH_ERROR
  1682. @trace
  1683. async def _maybe_kick_guest_users(self, event: EventBase) -> None:
  1684. if event.type != EventTypes.GuestAccess:
  1685. return
  1686. guest_access = event.content.get(EventContentFields.GUEST_ACCESS)
  1687. if guest_access == GuestAccess.CAN_JOIN:
  1688. return
  1689. current_state = await self._storage_controllers.state.get_current_state(
  1690. event.room_id
  1691. )
  1692. current_state_list = list(current_state.values())
  1693. await self._get_room_member_handler().kick_guest_users(current_state_list)
  1694. async def _check_for_soft_fail(
  1695. self,
  1696. event: EventBase,
  1697. context: EventContext,
  1698. origin: str,
  1699. ) -> None:
  1700. """Checks if we should soft fail the event; if so, marks the event as
  1701. such.
  1702. Does nothing for events in rooms with partial state, since we may not have an
  1703. accurate membership event for the sender in the current state.
  1704. Args:
  1705. event
  1706. context: The `EventContext` which we are about to persist the event with.
  1707. origin: The host the event originates from.
  1708. """
  1709. if await self._store.is_partial_state_room(event.room_id):
  1710. # We might not know the sender's membership in the current state, so don't
  1711. # soft fail anything. Even if we do have a membership for the sender in the
  1712. # current state, it may have been derived from state resolution between
  1713. # partial and full state and may not be accurate.
  1714. return
  1715. extrem_ids = await self._store.get_latest_event_ids_in_room(event.room_id)
  1716. prev_event_ids = set(event.prev_event_ids())
  1717. if extrem_ids == prev_event_ids:
  1718. # If they're the same then the current state is the same as the
  1719. # state at the event, so no point rechecking auth for soft fail.
  1720. return
  1721. room_version = await self._store.get_room_version_id(event.room_id)
  1722. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1723. # The event types we want to pull from the "current" state.
  1724. auth_types = auth_types_for_event(room_version_obj, event)
  1725. # Calculate the "current state".
  1726. seen_event_ids = await self._store.have_events_in_timeline(prev_event_ids)
  1727. has_missing_prevs = bool(prev_event_ids - seen_event_ids)
  1728. if has_missing_prevs:
  1729. # We don't have all the prev_events of this event, which means we have a
  1730. # gap in the graph, and the new event is going to become a new backwards
  1731. # extremity.
  1732. #
  1733. # In this case we want to be a little careful as we might have been
  1734. # down for a while and have an incorrect view of the current state,
  1735. # however we still want to do checks as gaps are easy to
  1736. # maliciously manufacture.
  1737. #
  1738. # So we use a "current state" that is actually a state
  1739. # resolution across the current forward extremities and the
  1740. # given state at the event. This should correctly handle cases
  1741. # like bans, especially with state res v2.
  1742. state_sets_d = await self._state_storage_controller.get_state_groups_ids(
  1743. event.room_id, extrem_ids
  1744. )
  1745. state_sets: List[StateMap[str]] = list(state_sets_d.values())
  1746. state_ids = await context.get_prev_state_ids()
  1747. state_sets.append(state_ids)
  1748. current_state_ids = (
  1749. await self._state_resolution_handler.resolve_events_with_store(
  1750. event.room_id,
  1751. room_version,
  1752. state_sets,
  1753. event_map=None,
  1754. state_res_store=StateResolutionStore(self._store),
  1755. )
  1756. )
  1757. else:
  1758. current_state_ids = (
  1759. await self._state_storage_controller.get_current_state_ids(
  1760. event.room_id, StateFilter.from_types(auth_types)
  1761. )
  1762. )
  1763. logger.debug(
  1764. "Doing soft-fail check for %s: state %s",
  1765. event.event_id,
  1766. current_state_ids,
  1767. )
  1768. # Now check if event pass auth against said current state
  1769. current_state_ids_list = [
  1770. e for k, e in current_state_ids.items() if k in auth_types
  1771. ]
  1772. current_auth_events = await self._store.get_events_as_list(
  1773. current_state_ids_list
  1774. )
  1775. try:
  1776. check_state_dependent_auth_rules(event, current_auth_events)
  1777. except AuthError as e:
  1778. logger.warning(
  1779. "Soft-failing %r (from %s) because %s",
  1780. event,
  1781. e,
  1782. origin,
  1783. extra={
  1784. "room_id": event.room_id,
  1785. "mxid": event.sender,
  1786. "hs": origin,
  1787. },
  1788. )
  1789. soft_failed_event_counter.inc()
  1790. event.internal_metadata.soft_failed = True
  1791. async def _load_or_fetch_auth_events_for_event(
  1792. self, destination: Optional[str], event: EventBase
  1793. ) -> Collection[EventBase]:
  1794. """Fetch this event's auth_events, from database or remote
  1795. Loads any of the auth_events that we already have from the database/cache. If
  1796. there are any that are missing, calls /event_auth to get the complete auth
  1797. chain for the event (and then attempts to load the auth_events again).
  1798. If any of the auth_events cannot be found, raises an AuthError. This can happen
  1799. for a number of reasons; eg: the events don't exist, or we were unable to talk
  1800. to `destination`, or we couldn't validate the signature on the event (which
  1801. in turn has multiple potential causes).
  1802. Args:
  1803. destination: where to send the /event_auth request. Typically the server
  1804. that sent us `event` in the first place.
  1805. If this is None, no attempt is made to load any missing auth events:
  1806. rather, an AssertionError is raised if there are any missing events.
  1807. event: the event whose auth_events we want
  1808. Returns:
  1809. all of the events listed in `event.auth_events_ids`, after deduplication
  1810. Raises:
  1811. AssertionError if some auth events were missing and no `destination` was
  1812. supplied.
  1813. AuthError if we were unable to fetch the auth_events for any reason.
  1814. """
  1815. event_auth_event_ids = set(event.auth_event_ids())
  1816. event_auth_events = await self._store.get_events(
  1817. event_auth_event_ids, allow_rejected=True
  1818. )
  1819. missing_auth_event_ids = event_auth_event_ids.difference(
  1820. event_auth_events.keys()
  1821. )
  1822. if not missing_auth_event_ids:
  1823. return event_auth_events.values()
  1824. if destination is None:
  1825. # this shouldn't happen: destination must be set unless we know we have already
  1826. # persisted the auth events.
  1827. raise AssertionError(
  1828. "_load_or_fetch_auth_events_for_event() called with no destination for "
  1829. "an event with missing auth_events"
  1830. )
  1831. logger.info(
  1832. "Event %s refers to unknown auth events %s: fetching auth chain",
  1833. event,
  1834. missing_auth_event_ids,
  1835. )
  1836. try:
  1837. await self._get_remote_auth_chain_for_event(
  1838. destination, event.room_id, event.event_id
  1839. )
  1840. except Exception as e:
  1841. logger.warning("Failed to get auth chain for %s: %s", event, e)
  1842. # in this case, it's very likely we still won't have all the auth
  1843. # events - but we pick that up below.
  1844. # try to fetch the auth events we missed list time.
  1845. extra_auth_events = await self._store.get_events(
  1846. missing_auth_event_ids, allow_rejected=True
  1847. )
  1848. missing_auth_event_ids.difference_update(extra_auth_events.keys())
  1849. event_auth_events.update(extra_auth_events)
  1850. if not missing_auth_event_ids:
  1851. return event_auth_events.values()
  1852. # we still don't have all the auth events.
  1853. logger.warning(
  1854. "Missing auth events for %s: %s",
  1855. event,
  1856. shortstr(missing_auth_event_ids),
  1857. )
  1858. # the fact we can't find the auth event doesn't mean it doesn't
  1859. # exist, which means it is premature to store `event` as rejected.
  1860. # instead we raise an AuthError, which will make the caller ignore it.
  1861. raise AuthError(code=HTTPStatus.FORBIDDEN, msg="Auth events could not be found")
  1862. @trace
  1863. @tag_args
  1864. async def _get_remote_auth_chain_for_event(
  1865. self, destination: str, room_id: str, event_id: str
  1866. ) -> None:
  1867. """If we are missing some of an event's auth events, attempt to request them
  1868. Args:
  1869. destination: where to fetch the auth tree from
  1870. room_id: the room in which we are lacking auth events
  1871. event_id: the event for which we are lacking auth events
  1872. """
  1873. try:
  1874. remote_events = await self._federation_client.get_event_auth(
  1875. destination, room_id, event_id
  1876. )
  1877. except RequestSendFailed as e1:
  1878. # The other side isn't around or doesn't implement the
  1879. # endpoint, so lets just bail out.
  1880. logger.info("Failed to get event auth from remote: %s", e1)
  1881. return
  1882. logger.info("/event_auth returned %i events", len(remote_events))
  1883. # `event` may be returned, but we should not yet process it.
  1884. remote_auth_events = (e for e in remote_events if e.event_id != event_id)
  1885. await self._auth_and_persist_outliers(room_id, remote_auth_events)
  1886. @trace
  1887. async def _run_push_actions_and_persist_event(
  1888. self, event: EventBase, context: EventContext, backfilled: bool = False
  1889. ) -> None:
  1890. """Run the push actions for a received event, and persist it.
  1891. Args:
  1892. event: The event itself.
  1893. context: The event context.
  1894. backfilled: True if the event was backfilled.
  1895. PartialStateConflictError: if attempting to persist a partial state event in
  1896. a room that has been un-partial stated.
  1897. """
  1898. # this method should not be called on outliers (those code paths call
  1899. # persist_events_and_notify directly.)
  1900. assert not event.internal_metadata.outlier
  1901. if not backfilled and not context.rejected:
  1902. min_depth = await self._store.get_min_depth(event.room_id)
  1903. if min_depth is None or min_depth > event.depth:
  1904. # XXX richvdh 2021/10/07: I don't really understand what this
  1905. # condition is doing. I think it's trying not to send pushes
  1906. # for events that predate our join - but that's not really what
  1907. # min_depth means, and anyway ancient events are a more general
  1908. # problem.
  1909. #
  1910. # for now I'm just going to log about it.
  1911. logger.info(
  1912. "Skipping push actions for old event with depth %s < %s",
  1913. event.depth,
  1914. min_depth,
  1915. )
  1916. else:
  1917. await self._bulk_push_rule_evaluator.action_for_events_by_user(
  1918. [(event, context)]
  1919. )
  1920. try:
  1921. await self.persist_events_and_notify(
  1922. event.room_id, [(event, context)], backfilled=backfilled
  1923. )
  1924. except Exception:
  1925. await self._store.remove_push_actions_from_staging(event.event_id)
  1926. raise
  1927. async def persist_events_and_notify(
  1928. self,
  1929. room_id: str,
  1930. event_and_contexts: Sequence[Tuple[EventBase, EventContext]],
  1931. backfilled: bool = False,
  1932. ) -> int:
  1933. """Persists events and tells the notifier/pushers about them, if
  1934. necessary.
  1935. Args:
  1936. room_id: The room ID of events being persisted.
  1937. event_and_contexts: Sequence of events with their associated
  1938. context that should be persisted. All events must belong to
  1939. the same room.
  1940. backfilled: Whether these events are a result of
  1941. backfilling or not
  1942. Returns:
  1943. The stream ID after which all events have been persisted.
  1944. Raises:
  1945. PartialStateConflictError: if attempting to persist a partial state event in
  1946. a room that has been un-partial stated.
  1947. """
  1948. if not event_and_contexts:
  1949. return self._store.get_room_max_stream_ordering()
  1950. instance = self._config.worker.events_shard_config.get_instance(room_id)
  1951. if instance != self._instance_name:
  1952. # Limit the number of events sent over replication. We choose 200
  1953. # here as that is what we default to in `max_request_body_size(..)`
  1954. result = {}
  1955. try:
  1956. for batch in batch_iter(event_and_contexts, 200):
  1957. result = await self._send_events(
  1958. instance_name=instance,
  1959. store=self._store,
  1960. room_id=room_id,
  1961. event_and_contexts=batch,
  1962. backfilled=backfilled,
  1963. )
  1964. except SynapseError as e:
  1965. if e.code == HTTPStatus.CONFLICT:
  1966. raise PartialStateConflictError()
  1967. raise
  1968. return result["max_stream_id"]
  1969. else:
  1970. assert self._storage_controllers.persistence
  1971. # Note that this returns the events that were persisted, which may not be
  1972. # the same as were passed in if some were deduplicated due to transaction IDs.
  1973. (
  1974. events,
  1975. max_stream_token,
  1976. ) = await self._storage_controllers.persistence.persist_events(
  1977. event_and_contexts, backfilled=backfilled
  1978. )
  1979. # After persistence we always need to notify replication there may
  1980. # be new data.
  1981. self._notifier.notify_replication()
  1982. if self._ephemeral_messages_enabled:
  1983. for event in events:
  1984. # If there's an expiry timestamp on the event, schedule its expiry.
  1985. self._message_handler.maybe_schedule_expiry(event)
  1986. if not backfilled: # Never notify for backfilled events
  1987. with start_active_span("notify_persisted_events"):
  1988. set_tag(
  1989. SynapseTags.RESULT_PREFIX + "event_ids",
  1990. str([ev.event_id for ev in events]),
  1991. )
  1992. set_tag(
  1993. SynapseTags.RESULT_PREFIX + "event_ids.length",
  1994. str(len(events)),
  1995. )
  1996. for event in events:
  1997. await self._notify_persisted_event(event, max_stream_token)
  1998. return max_stream_token.stream
  1999. async def _notify_persisted_event(
  2000. self, event: EventBase, max_stream_token: RoomStreamToken
  2001. ) -> None:
  2002. """Checks to see if notifier/pushers should be notified about the
  2003. event or not.
  2004. Args:
  2005. event:
  2006. max_stream_token: The max_stream_id returned by persist_events
  2007. """
  2008. extra_users = []
  2009. if event.type == EventTypes.Member:
  2010. target_user_id = event.state_key
  2011. # We notify for memberships if its an invite for one of our
  2012. # users
  2013. if event.internal_metadata.is_outlier():
  2014. if event.membership != Membership.INVITE:
  2015. if not self._is_mine_id(target_user_id):
  2016. return
  2017. target_user = UserID.from_string(target_user_id)
  2018. extra_users.append(target_user)
  2019. elif event.internal_metadata.is_outlier():
  2020. return
  2021. # the event has been persisted so it should have a stream ordering.
  2022. assert event.internal_metadata.stream_ordering
  2023. event_pos = PersistedEventPosition(
  2024. self._instance_name, event.internal_metadata.stream_ordering
  2025. )
  2026. await self._notifier.on_new_room_events(
  2027. [(event, event_pos)], max_stream_token, extra_users=extra_users
  2028. )
  2029. if event.type == EventTypes.Member and event.membership == Membership.JOIN:
  2030. # TODO retrieve the previous state, and exclude join -> join transitions
  2031. self._notifier.notify_user_joined_room(event.event_id, event.room_id)
  2032. # If this is a server ACL event, clear the cache in the storage controller.
  2033. if event.type == EventTypes.ServerACL:
  2034. self._state_storage_controller.get_server_acl_for_room.invalidate(
  2035. (event.room_id,)
  2036. )
  2037. def _sanity_check_event(self, ev: EventBase) -> None:
  2038. """
  2039. Do some early sanity checks of a received event
  2040. In particular, checks it doesn't have an excessive number of
  2041. prev_events or auth_events, which could cause a huge state resolution
  2042. or cascade of event fetches.
  2043. Args:
  2044. ev: event to be checked
  2045. Raises:
  2046. SynapseError if the event does not pass muster
  2047. """
  2048. if len(ev.prev_event_ids()) > 20:
  2049. logger.warning(
  2050. "Rejecting event %s which has %i prev_events",
  2051. ev.event_id,
  2052. len(ev.prev_event_ids()),
  2053. )
  2054. raise SynapseError(HTTPStatus.BAD_REQUEST, "Too many prev_events")
  2055. if len(ev.auth_event_ids()) > 10:
  2056. logger.warning(
  2057. "Rejecting event %s which has %i auth_events",
  2058. ev.event_id,
  2059. len(ev.auth_event_ids()),
  2060. )
  2061. raise SynapseError(HTTPStatus.BAD_REQUEST, "Too many auth_events")