federation.py 104 KB

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