federation.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Contains handlers for federation events."""
  17. import itertools
  18. import logging
  19. import sys
  20. from signedjson.key import decode_verify_key_bytes
  21. from signedjson.sign import verify_signed_json
  22. import six
  23. from six.moves import http_client
  24. from six import iteritems
  25. from twisted.internet import defer
  26. from unpaddedbase64 import decode_base64
  27. from ._base import BaseHandler
  28. from synapse.api.errors import (
  29. AuthError, FederationError, StoreError, CodeMessageException, SynapseError,
  30. FederationDeniedError,
  31. )
  32. from synapse.api.constants import EventTypes, Membership, RejectedReason
  33. from synapse.events.validator import EventValidator
  34. from synapse.util import unwrapFirstError, logcontext
  35. from synapse.util.metrics import measure_func
  36. from synapse.util.logutils import log_function
  37. from synapse.util.async import run_on_reactor, Linearizer
  38. from synapse.util.frozenutils import unfreeze
  39. from synapse.crypto.event_signing import (
  40. compute_event_signature, add_hashes_and_signatures,
  41. )
  42. from synapse.types import UserID, get_domain_from_id
  43. from synapse.events.utils import prune_event
  44. from synapse.util.retryutils import NotRetryingDestination
  45. from synapse.util.distributor import user_joined_room
  46. logger = logging.getLogger(__name__)
  47. class FederationHandler(BaseHandler):
  48. """Handles events that originated from federation.
  49. Responsible for:
  50. a) handling received Pdus before handing them on as Events to the rest
  51. of the home server (including auth and state conflict resoultion)
  52. b) converting events that were produced by local clients that may need
  53. to be sent to remote home servers.
  54. c) doing the necessary dances to invite remote users and join remote
  55. rooms.
  56. """
  57. def __init__(self, hs):
  58. super(FederationHandler, self).__init__(hs)
  59. self.hs = hs
  60. self.store = hs.get_datastore()
  61. self.replication_layer = hs.get_federation_client()
  62. self.state_handler = hs.get_state_handler()
  63. self.server_name = hs.hostname
  64. self.keyring = hs.get_keyring()
  65. self.action_generator = hs.get_action_generator()
  66. self.is_mine_id = hs.is_mine_id
  67. self.pusher_pool = hs.get_pusherpool()
  68. self.spam_checker = hs.get_spam_checker()
  69. self.event_creation_handler = hs.get_event_creation_handler()
  70. self._server_notices_mxid = hs.config.server_notices_mxid
  71. # When joining a room we need to queue any events for that room up
  72. self.room_queues = {}
  73. self._room_pdu_linearizer = Linearizer("fed_room_pdu")
  74. @defer.inlineCallbacks
  75. @log_function
  76. def on_receive_pdu(self, origin, pdu, get_missing=True):
  77. """ Process a PDU received via a federation /send/ transaction, or
  78. via backfill of missing prev_events
  79. Args:
  80. origin (str): server which initiated the /send/ transaction. Will
  81. be used to fetch missing events or state.
  82. pdu (FrozenEvent): received PDU
  83. get_missing (bool): True if we should fetch missing prev_events
  84. Returns (Deferred): completes with None
  85. """
  86. # We reprocess pdus when we have seen them only as outliers
  87. existing = yield self.get_persisted_pdu(
  88. origin, pdu.event_id, do_auth=False
  89. )
  90. # FIXME: Currently we fetch an event again when we already have it
  91. # if it has been marked as an outlier.
  92. already_seen = (
  93. existing and (
  94. not existing.internal_metadata.is_outlier()
  95. or pdu.internal_metadata.is_outlier()
  96. )
  97. )
  98. if already_seen:
  99. logger.debug("Already seen pdu %s", pdu.event_id)
  100. return
  101. # do some initial sanity-checking of the event. In particular, make
  102. # sure it doesn't have hundreds of prev_events or auth_events, which
  103. # could cause a huge state resolution or cascade of event fetches.
  104. try:
  105. self._sanity_check_event(pdu)
  106. except SynapseError as err:
  107. raise FederationError(
  108. "ERROR",
  109. err.code,
  110. err.msg,
  111. affected=pdu.event_id,
  112. )
  113. # If we are currently in the process of joining this room, then we
  114. # queue up events for later processing.
  115. if pdu.room_id in self.room_queues:
  116. logger.info("Ignoring PDU %s for room %s from %s for now; join "
  117. "in progress", pdu.event_id, pdu.room_id, origin)
  118. self.room_queues[pdu.room_id].append((pdu, origin))
  119. return
  120. # If we're no longer in the room just ditch the event entirely. This
  121. # is probably an old server that has come back and thinks we're still
  122. # in the room (or we've been rejoined to the room by a state reset).
  123. #
  124. # If we were never in the room then maybe our database got vaped and
  125. # we should check if we *are* in fact in the room. If we are then we
  126. # can magically rejoin the room.
  127. is_in_room = yield self.auth.check_host_in_room(
  128. pdu.room_id,
  129. self.server_name
  130. )
  131. if not is_in_room:
  132. was_in_room = yield self.store.was_host_joined(
  133. pdu.room_id, self.server_name,
  134. )
  135. if was_in_room:
  136. logger.info(
  137. "Ignoring PDU %s for room %s from %s as we've left the room!",
  138. pdu.event_id, pdu.room_id, origin,
  139. )
  140. return
  141. state = None
  142. auth_chain = []
  143. fetch_state = False
  144. # Get missing pdus if necessary.
  145. if not pdu.internal_metadata.is_outlier():
  146. # We only backfill backwards to the min depth.
  147. min_depth = yield self.get_min_depth_for_context(
  148. pdu.room_id
  149. )
  150. logger.debug(
  151. "_handle_new_pdu min_depth for %s: %d",
  152. pdu.room_id, min_depth
  153. )
  154. prevs = {e_id for e_id, _ in pdu.prev_events}
  155. seen = yield self.store.have_seen_events(prevs)
  156. if min_depth and pdu.depth < min_depth:
  157. # This is so that we don't notify the user about this
  158. # message, to work around the fact that some events will
  159. # reference really really old events we really don't want to
  160. # send to the clients.
  161. pdu.internal_metadata.outlier = True
  162. elif min_depth and pdu.depth > min_depth:
  163. if get_missing and prevs - seen:
  164. # If we're missing stuff, ensure we only fetch stuff one
  165. # at a time.
  166. logger.info(
  167. "Acquiring lock for room %r to fetch %d missing events: %r...",
  168. pdu.room_id, len(prevs - seen), list(prevs - seen)[:5],
  169. )
  170. with (yield self._room_pdu_linearizer.queue(pdu.room_id)):
  171. logger.info(
  172. "Acquired lock for room %r to fetch %d missing events",
  173. pdu.room_id, len(prevs - seen),
  174. )
  175. yield self._get_missing_events_for_pdu(
  176. origin, pdu, prevs, min_depth
  177. )
  178. # Update the set of things we've seen after trying to
  179. # fetch the missing stuff
  180. seen = yield self.store.have_seen_events(prevs)
  181. if not prevs - seen:
  182. logger.info(
  183. "Found all missing prev events for %s", pdu.event_id
  184. )
  185. elif prevs - seen:
  186. logger.info(
  187. "Not fetching %d missing events for room %r,event %s: %r...",
  188. len(prevs - seen), pdu.room_id, pdu.event_id,
  189. list(prevs - seen)[:5],
  190. )
  191. if prevs - seen:
  192. logger.info(
  193. "Still missing %d events for room %r: %r...",
  194. len(prevs - seen), pdu.room_id, list(prevs - seen)[:5]
  195. )
  196. fetch_state = True
  197. if fetch_state:
  198. # We need to get the state at this event, since we haven't
  199. # processed all the prev events.
  200. logger.debug(
  201. "_handle_new_pdu getting state for %s",
  202. pdu.room_id
  203. )
  204. try:
  205. state, auth_chain = yield self.replication_layer.get_state_for_room(
  206. origin, pdu.room_id, pdu.event_id,
  207. )
  208. except Exception:
  209. logger.exception("Failed to get state for event: %s", pdu.event_id)
  210. yield self._process_received_pdu(
  211. origin,
  212. pdu,
  213. state=state,
  214. auth_chain=auth_chain,
  215. )
  216. @defer.inlineCallbacks
  217. def _get_missing_events_for_pdu(self, origin, pdu, prevs, min_depth):
  218. """
  219. Args:
  220. origin (str): Origin of the pdu. Will be called to get the missing events
  221. pdu: received pdu
  222. prevs (set(str)): List of event ids which we are missing
  223. min_depth (int): Minimum depth of events to return.
  224. """
  225. # We recalculate seen, since it may have changed.
  226. seen = yield self.store.have_seen_events(prevs)
  227. if not prevs - seen:
  228. return
  229. latest = yield self.store.get_latest_event_ids_in_room(
  230. pdu.room_id
  231. )
  232. # We add the prev events that we have seen to the latest
  233. # list to ensure the remote server doesn't give them to us
  234. latest = set(latest)
  235. latest |= seen
  236. logger.info(
  237. "Missing %d events for room %r pdu %s: %r...",
  238. len(prevs - seen), pdu.room_id, pdu.event_id, list(prevs - seen)[:5]
  239. )
  240. # XXX: we set timeout to 10s to help workaround
  241. # https://github.com/matrix-org/synapse/issues/1733.
  242. # The reason is to avoid holding the linearizer lock
  243. # whilst processing inbound /send transactions, causing
  244. # FDs to stack up and block other inbound transactions
  245. # which empirically can currently take up to 30 minutes.
  246. #
  247. # N.B. this explicitly disables retry attempts.
  248. #
  249. # N.B. this also increases our chances of falling back to
  250. # fetching fresh state for the room if the missing event
  251. # can't be found, which slightly reduces our security.
  252. # it may also increase our DAG extremity count for the room,
  253. # causing additional state resolution? See #1760.
  254. # However, fetching state doesn't hold the linearizer lock
  255. # apparently.
  256. #
  257. # see https://github.com/matrix-org/synapse/pull/1744
  258. missing_events = yield self.replication_layer.get_missing_events(
  259. origin,
  260. pdu.room_id,
  261. earliest_events_ids=list(latest),
  262. latest_events=[pdu],
  263. limit=10,
  264. min_depth=min_depth,
  265. timeout=10000,
  266. )
  267. logger.info(
  268. "Got %d events: %r...",
  269. len(missing_events), [e.event_id for e in missing_events[:5]]
  270. )
  271. # We want to sort these by depth so we process them and
  272. # tell clients about them in order.
  273. missing_events.sort(key=lambda x: x.depth)
  274. for e in missing_events:
  275. logger.info("Handling found event %s", e.event_id)
  276. yield self.on_receive_pdu(
  277. origin,
  278. e,
  279. get_missing=False
  280. )
  281. @log_function
  282. @defer.inlineCallbacks
  283. def _process_received_pdu(self, origin, pdu, state, auth_chain):
  284. """ Called when we have a new pdu. We need to do auth checks and put it
  285. through the StateHandler.
  286. """
  287. event = pdu
  288. logger.debug("Processing event: %s", event)
  289. # FIXME (erikj): Awful hack to make the case where we are not currently
  290. # in the room work
  291. # If state and auth_chain are None, then we don't need to do this check
  292. # as we already know we have enough state in the DB to handle this
  293. # event.
  294. if state and auth_chain and not event.internal_metadata.is_outlier():
  295. is_in_room = yield self.auth.check_host_in_room(
  296. event.room_id,
  297. self.server_name
  298. )
  299. else:
  300. is_in_room = True
  301. if not is_in_room:
  302. logger.info(
  303. "Got event for room we're not in: %r %r",
  304. event.room_id, event.event_id
  305. )
  306. try:
  307. event_stream_id, max_stream_id = yield self._persist_auth_tree(
  308. origin, auth_chain, state, event
  309. )
  310. except AuthError as e:
  311. raise FederationError(
  312. "ERROR",
  313. e.code,
  314. e.msg,
  315. affected=event.event_id,
  316. )
  317. else:
  318. event_ids = set()
  319. if state:
  320. event_ids |= {e.event_id for e in state}
  321. if auth_chain:
  322. event_ids |= {e.event_id for e in auth_chain}
  323. seen_ids = yield self.store.have_seen_events(event_ids)
  324. if state and auth_chain is not None:
  325. # If we have any state or auth_chain given to us by the replication
  326. # layer, then we should handle them (if we haven't before.)
  327. event_infos = []
  328. for e in itertools.chain(auth_chain, state):
  329. if e.event_id in seen_ids:
  330. continue
  331. e.internal_metadata.outlier = True
  332. auth_ids = [e_id for e_id, _ in e.auth_events]
  333. auth = {
  334. (e.type, e.state_key): e for e in auth_chain
  335. if e.event_id in auth_ids or e.type == EventTypes.Create
  336. }
  337. event_infos.append({
  338. "event": e,
  339. "auth_events": auth,
  340. })
  341. seen_ids.add(e.event_id)
  342. yield self._handle_new_events(origin, event_infos)
  343. try:
  344. context, event_stream_id, max_stream_id = yield self._handle_new_event(
  345. origin,
  346. event,
  347. state=state,
  348. )
  349. except AuthError as e:
  350. raise FederationError(
  351. "ERROR",
  352. e.code,
  353. e.msg,
  354. affected=event.event_id,
  355. )
  356. room = yield self.store.get_room(event.room_id)
  357. if not room:
  358. try:
  359. yield self.store.store_room(
  360. room_id=event.room_id,
  361. room_creator_user_id="",
  362. is_public=False,
  363. )
  364. except StoreError:
  365. logger.exception("Failed to store room.")
  366. extra_users = []
  367. if event.type == EventTypes.Member:
  368. target_user_id = event.state_key
  369. target_user = UserID.from_string(target_user_id)
  370. extra_users.append(target_user)
  371. self.notifier.on_new_room_event(
  372. event, event_stream_id, max_stream_id,
  373. extra_users=extra_users
  374. )
  375. if event.type == EventTypes.Member:
  376. if event.membership == Membership.JOIN:
  377. # Only fire user_joined_room if the user has acutally
  378. # joined the room. Don't bother if the user is just
  379. # changing their profile info.
  380. newly_joined = True
  381. prev_state_id = context.prev_state_ids.get(
  382. (event.type, event.state_key)
  383. )
  384. if prev_state_id:
  385. prev_state = yield self.store.get_event(
  386. prev_state_id, allow_none=True,
  387. )
  388. if prev_state and prev_state.membership == Membership.JOIN:
  389. newly_joined = False
  390. if newly_joined:
  391. user = UserID.from_string(event.state_key)
  392. yield user_joined_room(self.distributor, user, event.room_id)
  393. @measure_func("_filter_events_for_server")
  394. @defer.inlineCallbacks
  395. def _filter_events_for_server(self, server_name, room_id, events):
  396. event_to_state_ids = yield self.store.get_state_ids_for_events(
  397. frozenset(e.event_id for e in events),
  398. types=(
  399. (EventTypes.RoomHistoryVisibility, ""),
  400. (EventTypes.Member, None),
  401. )
  402. )
  403. # We only want to pull out member events that correspond to the
  404. # server's domain.
  405. def check_match(id):
  406. try:
  407. return server_name == get_domain_from_id(id)
  408. except Exception:
  409. return False
  410. # Parses mapping `event_id -> (type, state_key) -> state event_id`
  411. # to get all state ids that we're interested in.
  412. event_map = yield self.store.get_events([
  413. e_id
  414. for key_to_eid in list(event_to_state_ids.values())
  415. for key, e_id in key_to_eid.items()
  416. if key[0] != EventTypes.Member or check_match(key[1])
  417. ])
  418. event_to_state = {
  419. e_id: {
  420. key: event_map[inner_e_id]
  421. for key, inner_e_id in key_to_eid.iteritems()
  422. if inner_e_id in event_map
  423. }
  424. for e_id, key_to_eid in event_to_state_ids.iteritems()
  425. }
  426. def redact_disallowed(event, state):
  427. if not state:
  428. return event
  429. history = state.get((EventTypes.RoomHistoryVisibility, ''), None)
  430. if history:
  431. visibility = history.content.get("history_visibility", "shared")
  432. if visibility in ["invited", "joined"]:
  433. # We now loop through all state events looking for
  434. # membership states for the requesting server to determine
  435. # if the server is either in the room or has been invited
  436. # into the room.
  437. for ev in state.itervalues():
  438. if ev.type != EventTypes.Member:
  439. continue
  440. try:
  441. domain = get_domain_from_id(ev.state_key)
  442. except Exception:
  443. continue
  444. if domain != server_name:
  445. continue
  446. memtype = ev.membership
  447. if memtype == Membership.JOIN:
  448. return event
  449. elif memtype == Membership.INVITE:
  450. if visibility == "invited":
  451. return event
  452. else:
  453. return prune_event(event)
  454. return event
  455. defer.returnValue([
  456. redact_disallowed(e, event_to_state[e.event_id])
  457. for e in events
  458. ])
  459. @log_function
  460. @defer.inlineCallbacks
  461. def backfill(self, dest, room_id, limit, extremities):
  462. """ Trigger a backfill request to `dest` for the given `room_id`
  463. This will attempt to get more events from the remote. If the other side
  464. has no new events to offer, this will return an empty list.
  465. As the events are received, we check their signatures, and also do some
  466. sanity-checking on them. If any of the backfilled events are invalid,
  467. this method throws a SynapseError.
  468. TODO: make this more useful to distinguish failures of the remote
  469. server from invalid events (there is probably no point in trying to
  470. re-fetch invalid events from every other HS in the room.)
  471. """
  472. if dest == self.server_name:
  473. raise SynapseError(400, "Can't backfill from self.")
  474. events = yield self.replication_layer.backfill(
  475. dest,
  476. room_id,
  477. limit=limit,
  478. extremities=extremities,
  479. )
  480. # ideally we'd sanity check the events here for excess prev_events etc,
  481. # but it's hard to reject events at this point without completely
  482. # breaking backfill in the same way that it is currently broken by
  483. # events whose signature we cannot verify (#3121).
  484. #
  485. # So for now we accept the events anyway. #3124 tracks this.
  486. #
  487. # for ev in events:
  488. # self._sanity_check_event(ev)
  489. # Don't bother processing events we already have.
  490. seen_events = yield self.store.have_events_in_timeline(
  491. set(e.event_id for e in events)
  492. )
  493. events = [e for e in events if e.event_id not in seen_events]
  494. if not events:
  495. defer.returnValue([])
  496. event_map = {e.event_id: e for e in events}
  497. event_ids = set(e.event_id for e in events)
  498. edges = [
  499. ev.event_id
  500. for ev in events
  501. if set(e_id for e_id, _ in ev.prev_events) - event_ids
  502. ]
  503. logger.info(
  504. "backfill: Got %d events with %d edges",
  505. len(events), len(edges),
  506. )
  507. # For each edge get the current state.
  508. auth_events = {}
  509. state_events = {}
  510. events_to_state = {}
  511. for e_id in edges:
  512. state, auth = yield self.replication_layer.get_state_for_room(
  513. destination=dest,
  514. room_id=room_id,
  515. event_id=e_id
  516. )
  517. auth_events.update({a.event_id: a for a in auth})
  518. auth_events.update({s.event_id: s for s in state})
  519. state_events.update({s.event_id: s for s in state})
  520. events_to_state[e_id] = state
  521. required_auth = set(
  522. a_id
  523. for event in events + state_events.values() + auth_events.values()
  524. for a_id, _ in event.auth_events
  525. )
  526. auth_events.update({
  527. e_id: event_map[e_id] for e_id in required_auth if e_id in event_map
  528. })
  529. missing_auth = required_auth - set(auth_events)
  530. failed_to_fetch = set()
  531. # Try and fetch any missing auth events from both DB and remote servers.
  532. # We repeatedly do this until we stop finding new auth events.
  533. while missing_auth - failed_to_fetch:
  534. logger.info("Missing auth for backfill: %r", missing_auth)
  535. ret_events = yield self.store.get_events(missing_auth - failed_to_fetch)
  536. auth_events.update(ret_events)
  537. required_auth.update(
  538. a_id for event in ret_events.values() for a_id, _ in event.auth_events
  539. )
  540. missing_auth = required_auth - set(auth_events)
  541. if missing_auth - failed_to_fetch:
  542. logger.info(
  543. "Fetching missing auth for backfill: %r",
  544. missing_auth - failed_to_fetch
  545. )
  546. results = yield logcontext.make_deferred_yieldable(defer.gatherResults(
  547. [
  548. logcontext.run_in_background(
  549. self.replication_layer.get_pdu,
  550. [dest],
  551. event_id,
  552. outlier=True,
  553. timeout=10000,
  554. )
  555. for event_id in missing_auth - failed_to_fetch
  556. ],
  557. consumeErrors=True
  558. )).addErrback(unwrapFirstError)
  559. auth_events.update({a.event_id: a for a in results if a})
  560. required_auth.update(
  561. a_id
  562. for event in results if event
  563. for a_id, _ in event.auth_events
  564. )
  565. missing_auth = required_auth - set(auth_events)
  566. failed_to_fetch = missing_auth - set(auth_events)
  567. seen_events = yield self.store.have_seen_events(
  568. set(auth_events.keys()) | set(state_events.keys())
  569. )
  570. ev_infos = []
  571. for a in auth_events.values():
  572. if a.event_id in seen_events:
  573. continue
  574. a.internal_metadata.outlier = True
  575. ev_infos.append({
  576. "event": a,
  577. "auth_events": {
  578. (auth_events[a_id].type, auth_events[a_id].state_key):
  579. auth_events[a_id]
  580. for a_id, _ in a.auth_events
  581. if a_id in auth_events
  582. }
  583. })
  584. for e_id in events_to_state:
  585. ev_infos.append({
  586. "event": event_map[e_id],
  587. "state": events_to_state[e_id],
  588. "auth_events": {
  589. (auth_events[a_id].type, auth_events[a_id].state_key):
  590. auth_events[a_id]
  591. for a_id, _ in event_map[e_id].auth_events
  592. if a_id in auth_events
  593. }
  594. })
  595. yield self._handle_new_events(
  596. dest, ev_infos,
  597. backfilled=True,
  598. )
  599. events.sort(key=lambda e: e.depth)
  600. for event in events:
  601. if event in events_to_state:
  602. continue
  603. # We store these one at a time since each event depends on the
  604. # previous to work out the state.
  605. # TODO: We can probably do something more clever here.
  606. yield self._handle_new_event(
  607. dest, event, backfilled=True,
  608. )
  609. defer.returnValue(events)
  610. @defer.inlineCallbacks
  611. def maybe_backfill(self, room_id, current_depth):
  612. """Checks the database to see if we should backfill before paginating,
  613. and if so do.
  614. """
  615. extremities = yield self.store.get_oldest_events_with_depth_in_room(
  616. room_id
  617. )
  618. if not extremities:
  619. logger.debug("Not backfilling as no extremeties found.")
  620. return
  621. # Check if we reached a point where we should start backfilling.
  622. sorted_extremeties_tuple = sorted(
  623. extremities.items(),
  624. key=lambda e: -int(e[1])
  625. )
  626. max_depth = sorted_extremeties_tuple[0][1]
  627. # We don't want to specify too many extremities as it causes the backfill
  628. # request URI to be too long.
  629. extremities = dict(sorted_extremeties_tuple[:5])
  630. if current_depth > max_depth:
  631. logger.debug(
  632. "Not backfilling as we don't need to. %d < %d",
  633. max_depth, current_depth,
  634. )
  635. return
  636. # Now we need to decide which hosts to hit first.
  637. # First we try hosts that are already in the room
  638. # TODO: HEURISTIC ALERT.
  639. curr_state = yield self.state_handler.get_current_state(room_id)
  640. def get_domains_from_state(state):
  641. """Get joined domains from state
  642. Args:
  643. state (dict[tuple, FrozenEvent]): State map from type/state
  644. key to event.
  645. Returns:
  646. list[tuple[str, int]]: Returns a list of servers with the
  647. lowest depth of their joins. Sorted by lowest depth first.
  648. """
  649. joined_users = [
  650. (state_key, int(event.depth))
  651. for (e_type, state_key), event in state.iteritems()
  652. if e_type == EventTypes.Member
  653. and event.membership == Membership.JOIN
  654. ]
  655. joined_domains = {}
  656. for u, d in joined_users:
  657. try:
  658. dom = get_domain_from_id(u)
  659. old_d = joined_domains.get(dom)
  660. if old_d:
  661. joined_domains[dom] = min(d, old_d)
  662. else:
  663. joined_domains[dom] = d
  664. except Exception:
  665. pass
  666. return sorted(joined_domains.iteritems(), key=lambda d: d[1])
  667. curr_domains = get_domains_from_state(curr_state)
  668. likely_domains = [
  669. domain for domain, depth in curr_domains
  670. if domain != self.server_name
  671. ]
  672. @defer.inlineCallbacks
  673. def try_backfill(domains):
  674. # TODO: Should we try multiple of these at a time?
  675. for dom in domains:
  676. try:
  677. yield self.backfill(
  678. dom, room_id,
  679. limit=100,
  680. extremities=extremities,
  681. )
  682. # If this succeeded then we probably already have the
  683. # appropriate stuff.
  684. # TODO: We can probably do something more intelligent here.
  685. defer.returnValue(True)
  686. except SynapseError as e:
  687. logger.info(
  688. "Failed to backfill from %s because %s",
  689. dom, e,
  690. )
  691. continue
  692. except CodeMessageException as e:
  693. if 400 <= e.code < 500:
  694. raise
  695. logger.info(
  696. "Failed to backfill from %s because %s",
  697. dom, e,
  698. )
  699. continue
  700. except NotRetryingDestination as e:
  701. logger.info(e.message)
  702. continue
  703. except FederationDeniedError as e:
  704. logger.info(e)
  705. continue
  706. except Exception as e:
  707. logger.exception(
  708. "Failed to backfill from %s because %s",
  709. dom, e,
  710. )
  711. continue
  712. defer.returnValue(False)
  713. success = yield try_backfill(likely_domains)
  714. if success:
  715. defer.returnValue(True)
  716. # Huh, well *those* domains didn't work out. Lets try some domains
  717. # from the time.
  718. tried_domains = set(likely_domains)
  719. tried_domains.add(self.server_name)
  720. event_ids = list(extremities.iterkeys())
  721. logger.debug("calling resolve_state_groups in _maybe_backfill")
  722. resolve = logcontext.preserve_fn(
  723. self.state_handler.resolve_state_groups_for_events
  724. )
  725. states = yield logcontext.make_deferred_yieldable(defer.gatherResults(
  726. [resolve(room_id, [e]) for e in event_ids],
  727. consumeErrors=True,
  728. ))
  729. # dict[str, dict[tuple, str]], a map from event_id to state map of
  730. # event_ids.
  731. states = dict(zip(event_ids, [s.state for s in states]))
  732. state_map = yield self.store.get_events(
  733. [e_id for ids in states.itervalues() for e_id in ids.itervalues()],
  734. get_prev_content=False
  735. )
  736. states = {
  737. key: {
  738. k: state_map[e_id]
  739. for k, e_id in state_dict.iteritems()
  740. if e_id in state_map
  741. } for key, state_dict in states.iteritems()
  742. }
  743. for e_id, _ in sorted_extremeties_tuple:
  744. likely_domains = get_domains_from_state(states[e_id])
  745. success = yield try_backfill([
  746. dom for dom, _ in likely_domains
  747. if dom not in tried_domains
  748. ])
  749. if success:
  750. defer.returnValue(True)
  751. tried_domains.update(dom for dom, _ in likely_domains)
  752. defer.returnValue(False)
  753. def _sanity_check_event(self, ev):
  754. """
  755. Do some early sanity checks of a received event
  756. In particular, checks it doesn't have an excessive number of
  757. prev_events or auth_events, which could cause a huge state resolution
  758. or cascade of event fetches.
  759. Args:
  760. ev (synapse.events.EventBase): event to be checked
  761. Returns: None
  762. Raises:
  763. SynapseError if the event does not pass muster
  764. """
  765. if len(ev.prev_events) > 20:
  766. logger.warn("Rejecting event %s which has %i prev_events",
  767. ev.event_id, len(ev.prev_events))
  768. raise SynapseError(
  769. http_client.BAD_REQUEST,
  770. "Too many prev_events",
  771. )
  772. if len(ev.auth_events) > 10:
  773. logger.warn("Rejecting event %s which has %i auth_events",
  774. ev.event_id, len(ev.auth_events))
  775. raise SynapseError(
  776. http_client.BAD_REQUEST,
  777. "Too many auth_events",
  778. )
  779. @defer.inlineCallbacks
  780. def send_invite(self, target_host, event):
  781. """ Sends the invite to the remote server for signing.
  782. Invites must be signed by the invitee's server before distribution.
  783. """
  784. pdu = yield self.replication_layer.send_invite(
  785. destination=target_host,
  786. room_id=event.room_id,
  787. event_id=event.event_id,
  788. pdu=event
  789. )
  790. defer.returnValue(pdu)
  791. @defer.inlineCallbacks
  792. def on_event_auth(self, event_id):
  793. event = yield self.store.get_event(event_id)
  794. auth = yield self.store.get_auth_chain(
  795. [auth_id for auth_id, _ in event.auth_events],
  796. include_given=True
  797. )
  798. for event in auth:
  799. event.signatures.update(
  800. compute_event_signature(
  801. event,
  802. self.hs.hostname,
  803. self.hs.config.signing_key[0]
  804. )
  805. )
  806. defer.returnValue([e for e in auth])
  807. @log_function
  808. @defer.inlineCallbacks
  809. def do_invite_join(self, target_hosts, room_id, joinee, content):
  810. """ Attempts to join the `joinee` to the room `room_id` via the
  811. server `target_host`.
  812. This first triggers a /make_join/ request that returns a partial
  813. event that we can fill out and sign. This is then sent to the
  814. remote server via /send_join/ which responds with the state at that
  815. event and the auth_chains.
  816. We suspend processing of any received events from this room until we
  817. have finished processing the join.
  818. """
  819. logger.debug("Joining %s to %s", joinee, room_id)
  820. origin, event = yield self._make_and_verify_event(
  821. target_hosts,
  822. room_id,
  823. joinee,
  824. "join",
  825. content,
  826. )
  827. # This shouldn't happen, because the RoomMemberHandler has a
  828. # linearizer lock which only allows one operation per user per room
  829. # at a time - so this is just paranoia.
  830. assert (room_id not in self.room_queues)
  831. self.room_queues[room_id] = []
  832. yield self.store.clean_room_for_join(room_id)
  833. handled_events = set()
  834. try:
  835. event = self._sign_event(event)
  836. # Try the host we successfully got a response to /make_join/
  837. # request first.
  838. try:
  839. target_hosts.remove(origin)
  840. target_hosts.insert(0, origin)
  841. except ValueError:
  842. pass
  843. ret = yield self.replication_layer.send_join(target_hosts, event)
  844. origin = ret["origin"]
  845. state = ret["state"]
  846. auth_chain = ret["auth_chain"]
  847. auth_chain.sort(key=lambda e: e.depth)
  848. handled_events.update([s.event_id for s in state])
  849. handled_events.update([a.event_id for a in auth_chain])
  850. handled_events.add(event.event_id)
  851. logger.debug("do_invite_join auth_chain: %s", auth_chain)
  852. logger.debug("do_invite_join state: %s", state)
  853. logger.debug("do_invite_join event: %s", event)
  854. try:
  855. yield self.store.store_room(
  856. room_id=room_id,
  857. room_creator_user_id="",
  858. is_public=False
  859. )
  860. except Exception:
  861. # FIXME
  862. pass
  863. event_stream_id, max_stream_id = yield self._persist_auth_tree(
  864. origin, auth_chain, state, event
  865. )
  866. self.notifier.on_new_room_event(
  867. event, event_stream_id, max_stream_id,
  868. extra_users=[joinee]
  869. )
  870. logger.debug("Finished joining %s to %s", joinee, room_id)
  871. finally:
  872. room_queue = self.room_queues[room_id]
  873. del self.room_queues[room_id]
  874. # we don't need to wait for the queued events to be processed -
  875. # it's just a best-effort thing at this point. We do want to do
  876. # them roughly in order, though, otherwise we'll end up making
  877. # lots of requests for missing prev_events which we do actually
  878. # have. Hence we fire off the deferred, but don't wait for it.
  879. logcontext.run_in_background(self._handle_queued_pdus, room_queue)
  880. defer.returnValue(True)
  881. @defer.inlineCallbacks
  882. def _handle_queued_pdus(self, room_queue):
  883. """Process PDUs which got queued up while we were busy send_joining.
  884. Args:
  885. room_queue (list[FrozenEvent, str]): list of PDUs to be processed
  886. and the servers that sent them
  887. """
  888. for p, origin in room_queue:
  889. try:
  890. logger.info("Processing queued PDU %s which was received "
  891. "while we were joining %s", p.event_id, p.room_id)
  892. yield self.on_receive_pdu(origin, p)
  893. except Exception as e:
  894. logger.warn(
  895. "Error handling queued PDU %s from %s: %s",
  896. p.event_id, origin, e)
  897. @defer.inlineCallbacks
  898. @log_function
  899. def on_make_join_request(self, room_id, user_id):
  900. """ We've received a /make_join/ request, so we create a partial
  901. join event for the room and return that. We do *not* persist or
  902. process it until the other server has signed it and sent it back.
  903. """
  904. event_content = {"membership": Membership.JOIN}
  905. builder = self.event_builder_factory.new({
  906. "type": EventTypes.Member,
  907. "content": event_content,
  908. "room_id": room_id,
  909. "sender": user_id,
  910. "state_key": user_id,
  911. })
  912. try:
  913. event, context = yield self.event_creation_handler.create_new_client_event(
  914. builder=builder,
  915. )
  916. except AuthError as e:
  917. logger.warn("Failed to create join %r because %s", event, e)
  918. raise e
  919. # The remote hasn't signed it yet, obviously. We'll do the full checks
  920. # when we get the event back in `on_send_join_request`
  921. yield self.auth.check_from_context(event, context, do_sig_check=False)
  922. defer.returnValue(event)
  923. @defer.inlineCallbacks
  924. @log_function
  925. def on_send_join_request(self, origin, pdu):
  926. """ We have received a join event for a room. Fully process it and
  927. respond with the current state and auth chains.
  928. """
  929. event = pdu
  930. logger.debug(
  931. "on_send_join_request: Got event: %s, signatures: %s",
  932. event.event_id,
  933. event.signatures,
  934. )
  935. event.internal_metadata.outlier = False
  936. # Send this event on behalf of the origin server.
  937. #
  938. # The reasons we have the destination server rather than the origin
  939. # server send it are slightly mysterious: the origin server should have
  940. # all the neccessary state once it gets the response to the send_join,
  941. # so it could send the event itself if it wanted to. It may be that
  942. # doing it this way reduces failure modes, or avoids certain attacks
  943. # where a new server selectively tells a subset of the federation that
  944. # it has joined.
  945. #
  946. # The fact is that, as of the current writing, Synapse doesn't send out
  947. # the join event over federation after joining, and changing it now
  948. # would introduce the danger of backwards-compatibility problems.
  949. event.internal_metadata.send_on_behalf_of = origin
  950. context, event_stream_id, max_stream_id = yield self._handle_new_event(
  951. origin, event
  952. )
  953. logger.debug(
  954. "on_send_join_request: After _handle_new_event: %s, sigs: %s",
  955. event.event_id,
  956. event.signatures,
  957. )
  958. extra_users = []
  959. if event.type == EventTypes.Member:
  960. target_user_id = event.state_key
  961. target_user = UserID.from_string(target_user_id)
  962. extra_users.append(target_user)
  963. self.notifier.on_new_room_event(
  964. event, event_stream_id, max_stream_id, extra_users=extra_users
  965. )
  966. if event.type == EventTypes.Member:
  967. if event.content["membership"] == Membership.JOIN:
  968. user = UserID.from_string(event.state_key)
  969. yield user_joined_room(self.distributor, user, event.room_id)
  970. state_ids = list(context.prev_state_ids.values())
  971. auth_chain = yield self.store.get_auth_chain(state_ids)
  972. state = yield self.store.get_events(list(context.prev_state_ids.values()))
  973. defer.returnValue({
  974. "state": list(state.values()),
  975. "auth_chain": auth_chain,
  976. })
  977. @defer.inlineCallbacks
  978. def on_invite_request(self, origin, pdu):
  979. """ We've got an invite event. Process and persist it. Sign it.
  980. Respond with the now signed event.
  981. """
  982. event = pdu
  983. if event.state_key is None:
  984. raise SynapseError(400, "The invite event did not have a state key")
  985. is_blocked = yield self.store.is_room_blocked(event.room_id)
  986. if is_blocked:
  987. raise SynapseError(403, "This room has been blocked on this server")
  988. if self.hs.config.block_non_admin_invites:
  989. raise SynapseError(403, "This server does not accept room invites")
  990. if not self.spam_checker.user_may_invite(
  991. event.sender, event.state_key, event.room_id,
  992. ):
  993. raise SynapseError(
  994. 403, "This user is not permitted to send invites to this server/user"
  995. )
  996. membership = event.content.get("membership")
  997. if event.type != EventTypes.Member or membership != Membership.INVITE:
  998. raise SynapseError(400, "The event was not an m.room.member invite event")
  999. sender_domain = get_domain_from_id(event.sender)
  1000. if sender_domain != origin:
  1001. raise SynapseError(400, "The invite event was not from the server sending it")
  1002. if not self.is_mine_id(event.state_key):
  1003. raise SynapseError(400, "The invite event must be for this server")
  1004. # block any attempts to invite the server notices mxid
  1005. if event.state_key == self._server_notices_mxid:
  1006. raise SynapseError(
  1007. http_client.FORBIDDEN,
  1008. "Cannot invite this user",
  1009. )
  1010. event.internal_metadata.outlier = True
  1011. event.internal_metadata.invite_from_remote = True
  1012. event.signatures.update(
  1013. compute_event_signature(
  1014. event,
  1015. self.hs.hostname,
  1016. self.hs.config.signing_key[0]
  1017. )
  1018. )
  1019. context = yield self.state_handler.compute_event_context(event)
  1020. event_stream_id, max_stream_id = yield self.store.persist_event(
  1021. event,
  1022. context=context,
  1023. )
  1024. target_user = UserID.from_string(event.state_key)
  1025. self.notifier.on_new_room_event(
  1026. event, event_stream_id, max_stream_id,
  1027. extra_users=[target_user],
  1028. )
  1029. defer.returnValue(event)
  1030. @defer.inlineCallbacks
  1031. def do_remotely_reject_invite(self, target_hosts, room_id, user_id):
  1032. origin, event = yield self._make_and_verify_event(
  1033. target_hosts,
  1034. room_id,
  1035. user_id,
  1036. "leave"
  1037. )
  1038. # Mark as outlier as we don't have any state for this event; we're not
  1039. # even in the room.
  1040. event.internal_metadata.outlier = True
  1041. event = self._sign_event(event)
  1042. # Try the host that we succesfully called /make_leave/ on first for
  1043. # the /send_leave/ request.
  1044. try:
  1045. target_hosts.remove(origin)
  1046. target_hosts.insert(0, origin)
  1047. except ValueError:
  1048. pass
  1049. yield self.replication_layer.send_leave(
  1050. target_hosts,
  1051. event
  1052. )
  1053. context = yield self.state_handler.compute_event_context(event)
  1054. event_stream_id, max_stream_id = yield self.store.persist_event(
  1055. event,
  1056. context=context,
  1057. )
  1058. target_user = UserID.from_string(event.state_key)
  1059. self.notifier.on_new_room_event(
  1060. event, event_stream_id, max_stream_id,
  1061. extra_users=[target_user],
  1062. )
  1063. defer.returnValue(event)
  1064. @defer.inlineCallbacks
  1065. def _make_and_verify_event(self, target_hosts, room_id, user_id, membership,
  1066. content={},):
  1067. origin, pdu = yield self.replication_layer.make_membership_event(
  1068. target_hosts,
  1069. room_id,
  1070. user_id,
  1071. membership,
  1072. content,
  1073. )
  1074. logger.debug("Got response to make_%s: %s", membership, pdu)
  1075. event = pdu
  1076. # We should assert some things.
  1077. # FIXME: Do this in a nicer way
  1078. assert(event.type == EventTypes.Member)
  1079. assert(event.user_id == user_id)
  1080. assert(event.state_key == user_id)
  1081. assert(event.room_id == room_id)
  1082. defer.returnValue((origin, event))
  1083. def _sign_event(self, event):
  1084. event.internal_metadata.outlier = False
  1085. builder = self.event_builder_factory.new(
  1086. unfreeze(event.get_pdu_json())
  1087. )
  1088. builder.event_id = self.event_builder_factory.create_event_id()
  1089. builder.origin = self.hs.hostname
  1090. if not hasattr(event, "signatures"):
  1091. builder.signatures = {}
  1092. add_hashes_and_signatures(
  1093. builder,
  1094. self.hs.hostname,
  1095. self.hs.config.signing_key[0],
  1096. )
  1097. return builder.build()
  1098. @defer.inlineCallbacks
  1099. @log_function
  1100. def on_make_leave_request(self, room_id, user_id):
  1101. """ We've received a /make_leave/ request, so we create a partial
  1102. join event for the room and return that. We do *not* persist or
  1103. process it until the other server has signed it and sent it back.
  1104. """
  1105. builder = self.event_builder_factory.new({
  1106. "type": EventTypes.Member,
  1107. "content": {"membership": Membership.LEAVE},
  1108. "room_id": room_id,
  1109. "sender": user_id,
  1110. "state_key": user_id,
  1111. })
  1112. event, context = yield self.event_creation_handler.create_new_client_event(
  1113. builder=builder,
  1114. )
  1115. try:
  1116. # The remote hasn't signed it yet, obviously. We'll do the full checks
  1117. # when we get the event back in `on_send_leave_request`
  1118. yield self.auth.check_from_context(event, context, do_sig_check=False)
  1119. except AuthError as e:
  1120. logger.warn("Failed to create new leave %r because %s", event, e)
  1121. raise e
  1122. defer.returnValue(event)
  1123. @defer.inlineCallbacks
  1124. @log_function
  1125. def on_send_leave_request(self, origin, pdu):
  1126. """ We have received a leave event for a room. Fully process it."""
  1127. event = pdu
  1128. logger.debug(
  1129. "on_send_leave_request: Got event: %s, signatures: %s",
  1130. event.event_id,
  1131. event.signatures,
  1132. )
  1133. event.internal_metadata.outlier = False
  1134. context, event_stream_id, max_stream_id = yield self._handle_new_event(
  1135. origin, event
  1136. )
  1137. logger.debug(
  1138. "on_send_leave_request: After _handle_new_event: %s, sigs: %s",
  1139. event.event_id,
  1140. event.signatures,
  1141. )
  1142. extra_users = []
  1143. if event.type == EventTypes.Member:
  1144. target_user_id = event.state_key
  1145. target_user = UserID.from_string(target_user_id)
  1146. extra_users.append(target_user)
  1147. self.notifier.on_new_room_event(
  1148. event, event_stream_id, max_stream_id, extra_users=extra_users
  1149. )
  1150. defer.returnValue(None)
  1151. @defer.inlineCallbacks
  1152. def get_state_for_pdu(self, room_id, event_id):
  1153. """Returns the state at the event. i.e. not including said event.
  1154. """
  1155. yield run_on_reactor()
  1156. state_groups = yield self.store.get_state_groups(
  1157. room_id, [event_id]
  1158. )
  1159. if state_groups:
  1160. _, state = list(iteritems(state_groups)).pop()
  1161. results = {
  1162. (e.type, e.state_key): e for e in state
  1163. }
  1164. event = yield self.store.get_event(event_id)
  1165. if event and event.is_state():
  1166. # Get previous state
  1167. if "replaces_state" in event.unsigned:
  1168. prev_id = event.unsigned["replaces_state"]
  1169. if prev_id != event.event_id:
  1170. prev_event = yield self.store.get_event(prev_id)
  1171. results[(event.type, event.state_key)] = prev_event
  1172. else:
  1173. del results[(event.type, event.state_key)]
  1174. res = list(results.values())
  1175. for event in res:
  1176. # We sign these again because there was a bug where we
  1177. # incorrectly signed things the first time round
  1178. if self.is_mine_id(event.event_id):
  1179. event.signatures.update(
  1180. compute_event_signature(
  1181. event,
  1182. self.hs.hostname,
  1183. self.hs.config.signing_key[0]
  1184. )
  1185. )
  1186. defer.returnValue(res)
  1187. else:
  1188. defer.returnValue([])
  1189. @defer.inlineCallbacks
  1190. def get_state_ids_for_pdu(self, room_id, event_id):
  1191. """Returns the state at the event. i.e. not including said event.
  1192. """
  1193. yield run_on_reactor()
  1194. state_groups = yield self.store.get_state_groups_ids(
  1195. room_id, [event_id]
  1196. )
  1197. if state_groups:
  1198. _, state = state_groups.items().pop()
  1199. results = state
  1200. event = yield self.store.get_event(event_id)
  1201. if event and event.is_state():
  1202. # Get previous state
  1203. if "replaces_state" in event.unsigned:
  1204. prev_id = event.unsigned["replaces_state"]
  1205. if prev_id != event.event_id:
  1206. results[(event.type, event.state_key)] = prev_id
  1207. else:
  1208. results.pop((event.type, event.state_key), None)
  1209. defer.returnValue(list(results.values()))
  1210. else:
  1211. defer.returnValue([])
  1212. @defer.inlineCallbacks
  1213. @log_function
  1214. def on_backfill_request(self, origin, room_id, pdu_list, limit):
  1215. in_room = yield self.auth.check_host_in_room(room_id, origin)
  1216. if not in_room:
  1217. raise AuthError(403, "Host not in room.")
  1218. events = yield self.store.get_backfill_events(
  1219. room_id,
  1220. pdu_list,
  1221. limit
  1222. )
  1223. events = yield self._filter_events_for_server(origin, room_id, events)
  1224. defer.returnValue(events)
  1225. @defer.inlineCallbacks
  1226. @log_function
  1227. def get_persisted_pdu(self, origin, event_id, do_auth=True):
  1228. """ Get a PDU from the database with given origin and id.
  1229. Returns:
  1230. Deferred: Results in a `Pdu`.
  1231. """
  1232. event = yield self.store.get_event(
  1233. event_id,
  1234. allow_none=True,
  1235. allow_rejected=True,
  1236. )
  1237. if event:
  1238. if self.is_mine_id(event.event_id):
  1239. # FIXME: This is a temporary work around where we occasionally
  1240. # return events slightly differently than when they were
  1241. # originally signed
  1242. event.signatures.update(
  1243. compute_event_signature(
  1244. event,
  1245. self.hs.hostname,
  1246. self.hs.config.signing_key[0]
  1247. )
  1248. )
  1249. if do_auth:
  1250. in_room = yield self.auth.check_host_in_room(
  1251. event.room_id,
  1252. origin
  1253. )
  1254. if not in_room:
  1255. raise AuthError(403, "Host not in room.")
  1256. events = yield self._filter_events_for_server(
  1257. origin, event.room_id, [event]
  1258. )
  1259. event = events[0]
  1260. defer.returnValue(event)
  1261. else:
  1262. defer.returnValue(None)
  1263. @log_function
  1264. def get_min_depth_for_context(self, context):
  1265. return self.store.get_min_depth(context)
  1266. @defer.inlineCallbacks
  1267. @log_function
  1268. def _handle_new_event(self, origin, event, state=None, auth_events=None,
  1269. backfilled=False):
  1270. context = yield self._prep_event(
  1271. origin, event,
  1272. state=state,
  1273. auth_events=auth_events,
  1274. )
  1275. try:
  1276. if not event.internal_metadata.is_outlier() and not backfilled:
  1277. yield self.action_generator.handle_push_actions_for_event(
  1278. event, context
  1279. )
  1280. event_stream_id, max_stream_id = yield self.store.persist_event(
  1281. event,
  1282. context=context,
  1283. backfilled=backfilled,
  1284. )
  1285. except: # noqa: E722, as we reraise the exception this is fine.
  1286. tp, value, tb = sys.exc_info()
  1287. logcontext.run_in_background(
  1288. self.store.remove_push_actions_from_staging,
  1289. event.event_id,
  1290. )
  1291. six.reraise(tp, value, tb)
  1292. if not backfilled:
  1293. # this intentionally does not yield: we don't care about the result
  1294. # and don't need to wait for it.
  1295. logcontext.run_in_background(
  1296. self.pusher_pool.on_new_notifications,
  1297. event_stream_id, max_stream_id,
  1298. )
  1299. defer.returnValue((context, event_stream_id, max_stream_id))
  1300. @defer.inlineCallbacks
  1301. def _handle_new_events(self, origin, event_infos, backfilled=False):
  1302. """Creates the appropriate contexts and persists events. The events
  1303. should not depend on one another, e.g. this should be used to persist
  1304. a bunch of outliers, but not a chunk of individual events that depend
  1305. on each other for state calculations.
  1306. """
  1307. contexts = yield logcontext.make_deferred_yieldable(defer.gatherResults(
  1308. [
  1309. logcontext.run_in_background(
  1310. self._prep_event,
  1311. origin,
  1312. ev_info["event"],
  1313. state=ev_info.get("state"),
  1314. auth_events=ev_info.get("auth_events"),
  1315. )
  1316. for ev_info in event_infos
  1317. ], consumeErrors=True,
  1318. ))
  1319. yield self.store.persist_events(
  1320. [
  1321. (ev_info["event"], context)
  1322. for ev_info, context in itertools.izip(event_infos, contexts)
  1323. ],
  1324. backfilled=backfilled,
  1325. )
  1326. @defer.inlineCallbacks
  1327. def _persist_auth_tree(self, origin, auth_events, state, event):
  1328. """Checks the auth chain is valid (and passes auth checks) for the
  1329. state and event. Then persists the auth chain and state atomically.
  1330. Persists the event seperately.
  1331. Will attempt to fetch missing auth events.
  1332. Args:
  1333. origin (str): Where the events came from
  1334. auth_events (list)
  1335. state (list)
  1336. event (Event)
  1337. Returns:
  1338. 2-tuple of (event_stream_id, max_stream_id) from the persist_event
  1339. call for `event`
  1340. """
  1341. events_to_context = {}
  1342. for e in itertools.chain(auth_events, state):
  1343. e.internal_metadata.outlier = True
  1344. ctx = yield self.state_handler.compute_event_context(e)
  1345. events_to_context[e.event_id] = ctx
  1346. event_map = {
  1347. e.event_id: e
  1348. for e in itertools.chain(auth_events, state, [event])
  1349. }
  1350. create_event = None
  1351. for e in auth_events:
  1352. if (e.type, e.state_key) == (EventTypes.Create, ""):
  1353. create_event = e
  1354. break
  1355. missing_auth_events = set()
  1356. for e in itertools.chain(auth_events, state, [event]):
  1357. for e_id, _ in e.auth_events:
  1358. if e_id not in event_map:
  1359. missing_auth_events.add(e_id)
  1360. for e_id in missing_auth_events:
  1361. m_ev = yield self.replication_layer.get_pdu(
  1362. [origin],
  1363. e_id,
  1364. outlier=True,
  1365. timeout=10000,
  1366. )
  1367. if m_ev and m_ev.event_id == e_id:
  1368. event_map[e_id] = m_ev
  1369. else:
  1370. logger.info("Failed to find auth event %r", e_id)
  1371. for e in itertools.chain(auth_events, state, [event]):
  1372. auth_for_e = {
  1373. (event_map[e_id].type, event_map[e_id].state_key): event_map[e_id]
  1374. for e_id, _ in e.auth_events
  1375. if e_id in event_map
  1376. }
  1377. if create_event:
  1378. auth_for_e[(EventTypes.Create, "")] = create_event
  1379. try:
  1380. self.auth.check(e, auth_events=auth_for_e)
  1381. except SynapseError as err:
  1382. # we may get SynapseErrors here as well as AuthErrors. For
  1383. # instance, there are a couple of (ancient) events in some
  1384. # rooms whose senders do not have the correct sigil; these
  1385. # cause SynapseErrors in auth.check. We don't want to give up
  1386. # the attempt to federate altogether in such cases.
  1387. logger.warn(
  1388. "Rejecting %s because %s",
  1389. e.event_id, err.msg
  1390. )
  1391. if e == event:
  1392. raise
  1393. events_to_context[e.event_id].rejected = RejectedReason.AUTH_ERROR
  1394. yield self.store.persist_events(
  1395. [
  1396. (e, events_to_context[e.event_id])
  1397. for e in itertools.chain(auth_events, state)
  1398. ],
  1399. )
  1400. new_event_context = yield self.state_handler.compute_event_context(
  1401. event, old_state=state
  1402. )
  1403. event_stream_id, max_stream_id = yield self.store.persist_event(
  1404. event, new_event_context,
  1405. )
  1406. defer.returnValue((event_stream_id, max_stream_id))
  1407. @defer.inlineCallbacks
  1408. def _prep_event(self, origin, event, state=None, auth_events=None):
  1409. """
  1410. Args:
  1411. origin:
  1412. event:
  1413. state:
  1414. auth_events:
  1415. Returns:
  1416. Deferred, which resolves to synapse.events.snapshot.EventContext
  1417. """
  1418. context = yield self.state_handler.compute_event_context(
  1419. event, old_state=state,
  1420. )
  1421. if not auth_events:
  1422. auth_events_ids = yield self.auth.compute_auth_events(
  1423. event, context.prev_state_ids, for_verification=True,
  1424. )
  1425. auth_events = yield self.store.get_events(auth_events_ids)
  1426. auth_events = {
  1427. (e.type, e.state_key): e for e in auth_events.values()
  1428. }
  1429. # This is a hack to fix some old rooms where the initial join event
  1430. # didn't reference the create event in its auth events.
  1431. if event.type == EventTypes.Member and not event.auth_events:
  1432. if len(event.prev_events) == 1 and event.depth < 5:
  1433. c = yield self.store.get_event(
  1434. event.prev_events[0][0],
  1435. allow_none=True,
  1436. )
  1437. if c and c.type == EventTypes.Create:
  1438. auth_events[(c.type, c.state_key)] = c
  1439. try:
  1440. yield self.do_auth(
  1441. origin, event, context, auth_events=auth_events
  1442. )
  1443. except AuthError as e:
  1444. logger.warn(
  1445. "Rejecting %s because %s",
  1446. event.event_id, e.msg
  1447. )
  1448. context.rejected = RejectedReason.AUTH_ERROR
  1449. if event.type == EventTypes.GuestAccess and not context.rejected:
  1450. yield self.maybe_kick_guest_users(event)
  1451. defer.returnValue(context)
  1452. @defer.inlineCallbacks
  1453. def on_query_auth(self, origin, event_id, remote_auth_chain, rejects,
  1454. missing):
  1455. # Just go through and process each event in `remote_auth_chain`. We
  1456. # don't want to fall into the trap of `missing` being wrong.
  1457. for e in remote_auth_chain:
  1458. try:
  1459. yield self._handle_new_event(origin, e)
  1460. except AuthError:
  1461. pass
  1462. # Now get the current auth_chain for the event.
  1463. event = yield self.store.get_event(event_id)
  1464. local_auth_chain = yield self.store.get_auth_chain(
  1465. [auth_id for auth_id, _ in event.auth_events],
  1466. include_given=True
  1467. )
  1468. # TODO: Check if we would now reject event_id. If so we need to tell
  1469. # everyone.
  1470. ret = yield self.construct_auth_difference(
  1471. local_auth_chain, remote_auth_chain
  1472. )
  1473. for event in ret["auth_chain"]:
  1474. event.signatures.update(
  1475. compute_event_signature(
  1476. event,
  1477. self.hs.hostname,
  1478. self.hs.config.signing_key[0]
  1479. )
  1480. )
  1481. logger.debug("on_query_auth returning: %s", ret)
  1482. defer.returnValue(ret)
  1483. @defer.inlineCallbacks
  1484. def on_get_missing_events(self, origin, room_id, earliest_events,
  1485. latest_events, limit, min_depth):
  1486. in_room = yield self.auth.check_host_in_room(
  1487. room_id,
  1488. origin
  1489. )
  1490. if not in_room:
  1491. raise AuthError(403, "Host not in room.")
  1492. limit = min(limit, 20)
  1493. min_depth = max(min_depth, 0)
  1494. missing_events = yield self.store.get_missing_events(
  1495. room_id=room_id,
  1496. earliest_events=earliest_events,
  1497. latest_events=latest_events,
  1498. limit=limit,
  1499. min_depth=min_depth,
  1500. )
  1501. defer.returnValue(missing_events)
  1502. @defer.inlineCallbacks
  1503. @log_function
  1504. def do_auth(self, origin, event, context, auth_events):
  1505. """
  1506. Args:
  1507. origin (str):
  1508. event (synapse.events.FrozenEvent):
  1509. context (synapse.events.snapshot.EventContext):
  1510. auth_events (dict[(str, str)->str]):
  1511. Returns:
  1512. defer.Deferred[None]
  1513. """
  1514. # Check if we have all the auth events.
  1515. current_state = set(e.event_id for e in auth_events.values())
  1516. event_auth_events = set(e_id for e_id, _ in event.auth_events)
  1517. if event.is_state():
  1518. event_key = (event.type, event.state_key)
  1519. else:
  1520. event_key = None
  1521. if event_auth_events - current_state:
  1522. # TODO: can we use store.have_seen_events here instead?
  1523. have_events = yield self.store.get_seen_events_with_rejections(
  1524. event_auth_events - current_state
  1525. )
  1526. else:
  1527. have_events = {}
  1528. have_events.update({
  1529. e.event_id: ""
  1530. for e in auth_events.values()
  1531. })
  1532. seen_events = set(have_events.keys())
  1533. missing_auth = event_auth_events - seen_events - current_state
  1534. if missing_auth:
  1535. logger.info("Missing auth: %s", missing_auth)
  1536. # If we don't have all the auth events, we need to get them.
  1537. try:
  1538. remote_auth_chain = yield self.replication_layer.get_event_auth(
  1539. origin, event.room_id, event.event_id
  1540. )
  1541. seen_remotes = yield self.store.have_seen_events(
  1542. [e.event_id for e in remote_auth_chain]
  1543. )
  1544. for e in remote_auth_chain:
  1545. if e.event_id in seen_remotes:
  1546. continue
  1547. if e.event_id == event.event_id:
  1548. continue
  1549. try:
  1550. auth_ids = [e_id for e_id, _ in e.auth_events]
  1551. auth = {
  1552. (e.type, e.state_key): e for e in remote_auth_chain
  1553. if e.event_id in auth_ids or e.type == EventTypes.Create
  1554. }
  1555. e.internal_metadata.outlier = True
  1556. logger.debug(
  1557. "do_auth %s missing_auth: %s",
  1558. event.event_id, e.event_id
  1559. )
  1560. yield self._handle_new_event(
  1561. origin, e, auth_events=auth
  1562. )
  1563. if e.event_id in event_auth_events:
  1564. auth_events[(e.type, e.state_key)] = e
  1565. except AuthError:
  1566. pass
  1567. have_events = yield self.store.get_seen_events_with_rejections(
  1568. [e_id for e_id, _ in event.auth_events]
  1569. )
  1570. seen_events = set(have_events.keys())
  1571. except Exception:
  1572. # FIXME:
  1573. logger.exception("Failed to get auth chain")
  1574. # FIXME: Assumes we have and stored all the state for all the
  1575. # prev_events
  1576. current_state = set(e.event_id for e in auth_events.values())
  1577. different_auth = event_auth_events - current_state
  1578. if different_auth and not event.internal_metadata.is_outlier():
  1579. # Do auth conflict res.
  1580. logger.info("Different auth: %s", different_auth)
  1581. different_events = yield logcontext.make_deferred_yieldable(
  1582. defer.gatherResults([
  1583. logcontext.run_in_background(
  1584. self.store.get_event,
  1585. d,
  1586. allow_none=True,
  1587. allow_rejected=False,
  1588. )
  1589. for d in different_auth
  1590. if d in have_events and not have_events[d]
  1591. ], consumeErrors=True)
  1592. ).addErrback(unwrapFirstError)
  1593. if different_events:
  1594. local_view = dict(auth_events)
  1595. remote_view = dict(auth_events)
  1596. remote_view.update({
  1597. (d.type, d.state_key): d for d in different_events if d
  1598. })
  1599. new_state = self.state_handler.resolve_events(
  1600. [list(local_view.values()), list(remote_view.values())],
  1601. event
  1602. )
  1603. auth_events.update(new_state)
  1604. current_state = set(e.event_id for e in auth_events.values())
  1605. different_auth = event_auth_events - current_state
  1606. yield self._update_context_for_auth_events(
  1607. event, context, auth_events, event_key,
  1608. )
  1609. if different_auth and not event.internal_metadata.is_outlier():
  1610. logger.info("Different auth after resolution: %s", different_auth)
  1611. # Only do auth resolution if we have something new to say.
  1612. # We can't rove an auth failure.
  1613. do_resolution = False
  1614. provable = [
  1615. RejectedReason.NOT_ANCESTOR, RejectedReason.NOT_ANCESTOR,
  1616. ]
  1617. for e_id in different_auth:
  1618. if e_id in have_events:
  1619. if have_events[e_id] in provable:
  1620. do_resolution = True
  1621. break
  1622. if do_resolution:
  1623. # 1. Get what we think is the auth chain.
  1624. auth_ids = yield self.auth.compute_auth_events(
  1625. event, context.prev_state_ids
  1626. )
  1627. local_auth_chain = yield self.store.get_auth_chain(
  1628. auth_ids, include_given=True
  1629. )
  1630. try:
  1631. # 2. Get remote difference.
  1632. result = yield self.replication_layer.query_auth(
  1633. origin,
  1634. event.room_id,
  1635. event.event_id,
  1636. local_auth_chain,
  1637. )
  1638. seen_remotes = yield self.store.have_seen_events(
  1639. [e.event_id for e in result["auth_chain"]]
  1640. )
  1641. # 3. Process any remote auth chain events we haven't seen.
  1642. for ev in result["auth_chain"]:
  1643. if ev.event_id in seen_remotes:
  1644. continue
  1645. if ev.event_id == event.event_id:
  1646. continue
  1647. try:
  1648. auth_ids = [e_id for e_id, _ in ev.auth_events]
  1649. auth = {
  1650. (e.type, e.state_key): e
  1651. for e in result["auth_chain"]
  1652. if e.event_id in auth_ids
  1653. or event.type == EventTypes.Create
  1654. }
  1655. ev.internal_metadata.outlier = True
  1656. logger.debug(
  1657. "do_auth %s different_auth: %s",
  1658. event.event_id, e.event_id
  1659. )
  1660. yield self._handle_new_event(
  1661. origin, ev, auth_events=auth
  1662. )
  1663. if ev.event_id in event_auth_events:
  1664. auth_events[(ev.type, ev.state_key)] = ev
  1665. except AuthError:
  1666. pass
  1667. except Exception:
  1668. # FIXME:
  1669. logger.exception("Failed to query auth chain")
  1670. # 4. Look at rejects and their proofs.
  1671. # TODO.
  1672. yield self._update_context_for_auth_events(
  1673. event, context, auth_events, event_key,
  1674. )
  1675. try:
  1676. self.auth.check(event, auth_events=auth_events)
  1677. except AuthError as e:
  1678. logger.warn("Failed auth resolution for %r because %s", event, e)
  1679. raise e
  1680. @defer.inlineCallbacks
  1681. def _update_context_for_auth_events(self, event, context, auth_events,
  1682. event_key):
  1683. """Update the state_ids in an event context after auth event resolution,
  1684. storing the changes as a new state group.
  1685. Args:
  1686. event (Event): The event we're handling the context for
  1687. context (synapse.events.snapshot.EventContext): event context
  1688. to be updated
  1689. auth_events (dict[(str, str)->str]): Events to update in the event
  1690. context.
  1691. event_key ((str, str)): (type, state_key) for the current event.
  1692. this will not be included in the current_state in the context.
  1693. """
  1694. state_updates = {
  1695. k: a.event_id for k, a in iteritems(auth_events)
  1696. if k != event_key
  1697. }
  1698. context.current_state_ids = dict(context.current_state_ids)
  1699. context.current_state_ids.update(state_updates)
  1700. if context.delta_ids is not None:
  1701. context.delta_ids = dict(context.delta_ids)
  1702. context.delta_ids.update(state_updates)
  1703. context.prev_state_ids = dict(context.prev_state_ids)
  1704. context.prev_state_ids.update({
  1705. k: a.event_id for k, a in iteritems(auth_events)
  1706. })
  1707. context.state_group = yield self.store.store_state_group(
  1708. event.event_id,
  1709. event.room_id,
  1710. prev_group=context.prev_group,
  1711. delta_ids=context.delta_ids,
  1712. current_state_ids=context.current_state_ids,
  1713. )
  1714. @defer.inlineCallbacks
  1715. def construct_auth_difference(self, local_auth, remote_auth):
  1716. """ Given a local and remote auth chain, find the differences. This
  1717. assumes that we have already processed all events in remote_auth
  1718. Params:
  1719. local_auth (list)
  1720. remote_auth (list)
  1721. Returns:
  1722. dict
  1723. """
  1724. logger.debug("construct_auth_difference Start!")
  1725. # TODO: Make sure we are OK with local_auth or remote_auth having more
  1726. # auth events in them than strictly necessary.
  1727. def sort_fun(ev):
  1728. return ev.depth, ev.event_id
  1729. logger.debug("construct_auth_difference after sort_fun!")
  1730. # We find the differences by starting at the "bottom" of each list
  1731. # and iterating up on both lists. The lists are ordered by depth and
  1732. # then event_id, we iterate up both lists until we find the event ids
  1733. # don't match. Then we look at depth/event_id to see which side is
  1734. # missing that event, and iterate only up that list. Repeat.
  1735. remote_list = list(remote_auth)
  1736. remote_list.sort(key=sort_fun)
  1737. local_list = list(local_auth)
  1738. local_list.sort(key=sort_fun)
  1739. local_iter = iter(local_list)
  1740. remote_iter = iter(remote_list)
  1741. logger.debug("construct_auth_difference before get_next!")
  1742. def get_next(it, opt=None):
  1743. try:
  1744. return next(it)
  1745. except Exception:
  1746. return opt
  1747. current_local = get_next(local_iter)
  1748. current_remote = get_next(remote_iter)
  1749. logger.debug("construct_auth_difference before while")
  1750. missing_remotes = []
  1751. missing_locals = []
  1752. while current_local or current_remote:
  1753. if current_remote is None:
  1754. missing_locals.append(current_local)
  1755. current_local = get_next(local_iter)
  1756. continue
  1757. if current_local is None:
  1758. missing_remotes.append(current_remote)
  1759. current_remote = get_next(remote_iter)
  1760. continue
  1761. if current_local.event_id == current_remote.event_id:
  1762. current_local = get_next(local_iter)
  1763. current_remote = get_next(remote_iter)
  1764. continue
  1765. if current_local.depth < current_remote.depth:
  1766. missing_locals.append(current_local)
  1767. current_local = get_next(local_iter)
  1768. continue
  1769. if current_local.depth > current_remote.depth:
  1770. missing_remotes.append(current_remote)
  1771. current_remote = get_next(remote_iter)
  1772. continue
  1773. # They have the same depth, so we fall back to the event_id order
  1774. if current_local.event_id < current_remote.event_id:
  1775. missing_locals.append(current_local)
  1776. current_local = get_next(local_iter)
  1777. if current_local.event_id > current_remote.event_id:
  1778. missing_remotes.append(current_remote)
  1779. current_remote = get_next(remote_iter)
  1780. continue
  1781. logger.debug("construct_auth_difference after while")
  1782. # missing locals should be sent to the server
  1783. # We should find why we are missing remotes, as they will have been
  1784. # rejected.
  1785. # Remove events from missing_remotes if they are referencing a missing
  1786. # remote. We only care about the "root" rejected ones.
  1787. missing_remote_ids = [e.event_id for e in missing_remotes]
  1788. base_remote_rejected = list(missing_remotes)
  1789. for e in missing_remotes:
  1790. for e_id, _ in e.auth_events:
  1791. if e_id in missing_remote_ids:
  1792. try:
  1793. base_remote_rejected.remove(e)
  1794. except ValueError:
  1795. pass
  1796. reason_map = {}
  1797. for e in base_remote_rejected:
  1798. reason = yield self.store.get_rejection_reason(e.event_id)
  1799. if reason is None:
  1800. # TODO: e is not in the current state, so we should
  1801. # construct some proof of that.
  1802. continue
  1803. reason_map[e.event_id] = reason
  1804. if reason == RejectedReason.AUTH_ERROR:
  1805. pass
  1806. elif reason == RejectedReason.REPLACED:
  1807. # TODO: Get proof
  1808. pass
  1809. elif reason == RejectedReason.NOT_ANCESTOR:
  1810. # TODO: Get proof.
  1811. pass
  1812. logger.debug("construct_auth_difference returning")
  1813. defer.returnValue({
  1814. "auth_chain": local_auth,
  1815. "rejects": {
  1816. e.event_id: {
  1817. "reason": reason_map[e.event_id],
  1818. "proof": None,
  1819. }
  1820. for e in base_remote_rejected
  1821. },
  1822. "missing": [e.event_id for e in missing_locals],
  1823. })
  1824. @defer.inlineCallbacks
  1825. @log_function
  1826. def exchange_third_party_invite(
  1827. self,
  1828. sender_user_id,
  1829. target_user_id,
  1830. room_id,
  1831. signed,
  1832. ):
  1833. third_party_invite = {
  1834. "signed": signed,
  1835. }
  1836. event_dict = {
  1837. "type": EventTypes.Member,
  1838. "content": {
  1839. "membership": Membership.INVITE,
  1840. "third_party_invite": third_party_invite,
  1841. },
  1842. "room_id": room_id,
  1843. "sender": sender_user_id,
  1844. "state_key": target_user_id,
  1845. }
  1846. if (yield self.auth.check_host_in_room(room_id, self.hs.hostname)):
  1847. builder = self.event_builder_factory.new(event_dict)
  1848. EventValidator().validate_new(builder)
  1849. event, context = yield self.event_creation_handler.create_new_client_event(
  1850. builder=builder
  1851. )
  1852. event, context = yield self.add_display_name_to_third_party_invite(
  1853. event_dict, event, context
  1854. )
  1855. try:
  1856. yield self.auth.check_from_context(event, context)
  1857. except AuthError as e:
  1858. logger.warn("Denying new third party invite %r because %s", event, e)
  1859. raise e
  1860. yield self._check_signature(event, context)
  1861. member_handler = self.hs.get_room_member_handler()
  1862. yield member_handler.send_membership_event(None, event, context)
  1863. else:
  1864. destinations = set(x.split(":", 1)[-1] for x in (sender_user_id, room_id))
  1865. yield self.replication_layer.forward_third_party_invite(
  1866. destinations,
  1867. room_id,
  1868. event_dict,
  1869. )
  1870. @defer.inlineCallbacks
  1871. @log_function
  1872. def on_exchange_third_party_invite_request(self, origin, room_id, event_dict):
  1873. """Handle an exchange_third_party_invite request from a remote server
  1874. The remote server will call this when it wants to turn a 3pid invite
  1875. into a normal m.room.member invite.
  1876. Returns:
  1877. Deferred: resolves (to None)
  1878. """
  1879. builder = self.event_builder_factory.new(event_dict)
  1880. event, context = yield self.event_creation_handler.create_new_client_event(
  1881. builder=builder,
  1882. )
  1883. event, context = yield self.add_display_name_to_third_party_invite(
  1884. event_dict, event, context
  1885. )
  1886. try:
  1887. self.auth.check_from_context(event, context)
  1888. except AuthError as e:
  1889. logger.warn("Denying third party invite %r because %s", event, e)
  1890. raise e
  1891. yield self._check_signature(event, context)
  1892. # XXX we send the invite here, but send_membership_event also sends it,
  1893. # so we end up making two requests. I think this is redundant.
  1894. returned_invite = yield self.send_invite(origin, event)
  1895. # TODO: Make sure the signatures actually are correct.
  1896. event.signatures.update(returned_invite.signatures)
  1897. member_handler = self.hs.get_room_member_handler()
  1898. yield member_handler.send_membership_event(None, event, context)
  1899. @defer.inlineCallbacks
  1900. def add_display_name_to_third_party_invite(self, event_dict, event, context):
  1901. key = (
  1902. EventTypes.ThirdPartyInvite,
  1903. event.content["third_party_invite"]["signed"]["token"]
  1904. )
  1905. original_invite = None
  1906. original_invite_id = context.prev_state_ids.get(key)
  1907. if original_invite_id:
  1908. original_invite = yield self.store.get_event(
  1909. original_invite_id, allow_none=True
  1910. )
  1911. if original_invite:
  1912. display_name = original_invite.content["display_name"]
  1913. event_dict["content"]["third_party_invite"]["display_name"] = display_name
  1914. else:
  1915. logger.info(
  1916. "Could not find invite event for third_party_invite: %r",
  1917. event_dict
  1918. )
  1919. # We don't discard here as this is not the appropriate place to do
  1920. # auth checks. If we need the invite and don't have it then the
  1921. # auth check code will explode appropriately.
  1922. builder = self.event_builder_factory.new(event_dict)
  1923. EventValidator().validate_new(builder)
  1924. event, context = yield self.event_creation_handler.create_new_client_event(
  1925. builder=builder,
  1926. )
  1927. defer.returnValue((event, context))
  1928. @defer.inlineCallbacks
  1929. def _check_signature(self, event, context):
  1930. """
  1931. Checks that the signature in the event is consistent with its invite.
  1932. Args:
  1933. event (Event): The m.room.member event to check
  1934. context (EventContext):
  1935. Raises:
  1936. AuthError: if signature didn't match any keys, or key has been
  1937. revoked,
  1938. SynapseError: if a transient error meant a key couldn't be checked
  1939. for revocation.
  1940. """
  1941. signed = event.content["third_party_invite"]["signed"]
  1942. token = signed["token"]
  1943. invite_event_id = context.prev_state_ids.get(
  1944. (EventTypes.ThirdPartyInvite, token,)
  1945. )
  1946. invite_event = None
  1947. if invite_event_id:
  1948. invite_event = yield self.store.get_event(invite_event_id, allow_none=True)
  1949. if not invite_event:
  1950. raise AuthError(403, "Could not find invite")
  1951. last_exception = None
  1952. for public_key_object in self.hs.get_auth().get_public_keys(invite_event):
  1953. try:
  1954. for server, signature_block in signed["signatures"].items():
  1955. for key_name, encoded_signature in signature_block.items():
  1956. if not key_name.startswith("ed25519:"):
  1957. continue
  1958. public_key = public_key_object["public_key"]
  1959. verify_key = decode_verify_key_bytes(
  1960. key_name,
  1961. decode_base64(public_key)
  1962. )
  1963. verify_signed_json(signed, server, verify_key)
  1964. if "key_validity_url" in public_key_object:
  1965. yield self._check_key_revocation(
  1966. public_key,
  1967. public_key_object["key_validity_url"]
  1968. )
  1969. return
  1970. except Exception as e:
  1971. last_exception = e
  1972. raise last_exception
  1973. @defer.inlineCallbacks
  1974. def _check_key_revocation(self, public_key, url):
  1975. """
  1976. Checks whether public_key has been revoked.
  1977. Args:
  1978. public_key (str): base-64 encoded public key.
  1979. url (str): Key revocation URL.
  1980. Raises:
  1981. AuthError: if they key has been revoked.
  1982. SynapseError: if a transient error meant a key couldn't be checked
  1983. for revocation.
  1984. """
  1985. try:
  1986. response = yield self.hs.get_simple_http_client().get_json(
  1987. url,
  1988. {"public_key": public_key}
  1989. )
  1990. except Exception:
  1991. raise SynapseError(
  1992. 502,
  1993. "Third party certificate could not be checked"
  1994. )
  1995. if "valid" not in response or not response["valid"]:
  1996. raise AuthError(403, "Third party certificate was invalid")