federation.py 83 KB

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