federation.py 113 KB

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