federation.py 114 KB

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