federation.py 113 KB

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