federation.py 79 KB

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