federation.py 111 KB

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