federation.py 118 KB

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