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.
 
 
 
 
 
 

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