message.py 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2017-2018 New Vector Ltd
  3. # Copyright 2019-2020 The Matrix.org Foundation C.I.C.
  4. # Copyrignt 2020 Sorunome
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. import random
  19. from http import HTTPStatus
  20. from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Tuple
  21. from canonicaljson import encode_canonical_json
  22. from twisted.internet.interfaces import IDelayedCall
  23. from synapse import event_auth
  24. from synapse.api.constants import (
  25. EventContentFields,
  26. EventTypes,
  27. GuestAccess,
  28. HistoryVisibility,
  29. Membership,
  30. RelationTypes,
  31. UserTypes,
  32. )
  33. from synapse.api.errors import (
  34. AuthError,
  35. Codes,
  36. ConsentNotGivenError,
  37. NotFoundError,
  38. PartialStateConflictError,
  39. ShadowBanError,
  40. SynapseError,
  41. UnstableSpecAuthError,
  42. UnsupportedRoomVersionError,
  43. )
  44. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  45. from synapse.api.urls import ConsentURIBuilder
  46. from synapse.event_auth import validate_event_for_room_version
  47. from synapse.events import EventBase, relation_from_event
  48. from synapse.events.builder import EventBuilder
  49. from synapse.events.snapshot import EventContext, UnpersistedEventContextBase
  50. from synapse.events.utils import SerializeEventConfig, maybe_upsert_event_field
  51. from synapse.events.validator import EventValidator
  52. from synapse.handlers.directory import DirectoryHandler
  53. from synapse.logging import opentracing
  54. from synapse.logging.context import make_deferred_yieldable, run_in_background
  55. from synapse.metrics.background_process_metrics import run_as_background_process
  56. from synapse.replication.http.send_event import ReplicationSendEventRestServlet
  57. from synapse.replication.http.send_events import ReplicationSendEventsRestServlet
  58. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  59. from synapse.types import (
  60. MutableStateMap,
  61. PersistedEventPosition,
  62. Requester,
  63. RoomAlias,
  64. StateMap,
  65. StreamToken,
  66. UserID,
  67. create_requester,
  68. )
  69. from synapse.types.state import StateFilter
  70. from synapse.util import json_decoder, json_encoder, log_failure, unwrapFirstError
  71. from synapse.util.async_helpers import Linearizer, gather_results
  72. from synapse.util.caches.expiringcache import ExpiringCache
  73. from synapse.util.metrics import measure_func
  74. from synapse.visibility import get_effective_room_visibility_from_state
  75. if TYPE_CHECKING:
  76. from synapse.events.third_party_rules import ThirdPartyEventRules
  77. from synapse.server import HomeServer
  78. logger = logging.getLogger(__name__)
  79. class MessageHandler:
  80. """Contains some read only APIs to get state about a room"""
  81. def __init__(self, hs: "HomeServer"):
  82. self.auth = hs.get_auth()
  83. self.clock = hs.get_clock()
  84. self.state = hs.get_state_handler()
  85. self.store = hs.get_datastores().main
  86. self._storage_controllers = hs.get_storage_controllers()
  87. self._state_storage_controller = self._storage_controllers.state
  88. self._event_serializer = hs.get_event_client_serializer()
  89. self._ephemeral_events_enabled = hs.config.server.enable_ephemeral_messages
  90. # The scheduled call to self._expire_event. None if no call is currently
  91. # scheduled.
  92. self._scheduled_expiry: Optional[IDelayedCall] = None
  93. if not hs.config.worker.worker_app:
  94. run_as_background_process(
  95. "_schedule_next_expiry", self._schedule_next_expiry
  96. )
  97. async def get_room_data(
  98. self,
  99. requester: Requester,
  100. room_id: str,
  101. event_type: str,
  102. state_key: str,
  103. ) -> Optional[EventBase]:
  104. """Get data from a room.
  105. Args:
  106. requester: The user who did the request.
  107. room_id
  108. event_type
  109. state_key
  110. Returns:
  111. The path data content.
  112. Raises:
  113. SynapseError or AuthError if the user is not in the room
  114. """
  115. (
  116. membership,
  117. membership_event_id,
  118. ) = await self.auth.check_user_in_room_or_world_readable(
  119. room_id, requester, allow_departed_users=True
  120. )
  121. if membership == Membership.JOIN:
  122. data = await self._storage_controllers.state.get_current_state_event(
  123. room_id, event_type, state_key
  124. )
  125. elif membership == Membership.LEAVE:
  126. key = (event_type, state_key)
  127. # If the membership is not JOIN, then the event ID should exist.
  128. assert (
  129. membership_event_id is not None
  130. ), "check_user_in_room_or_world_readable returned invalid data"
  131. room_state = await self._state_storage_controller.get_state_for_events(
  132. [membership_event_id], StateFilter.from_types([key])
  133. )
  134. data = room_state[membership_event_id].get(key)
  135. else:
  136. # check_user_in_room_or_world_readable, if it doesn't raise an AuthError, should
  137. # only ever return a Membership.JOIN/LEAVE object
  138. #
  139. # Safeguard in case it returned something else
  140. logger.error(
  141. "Attempted to retrieve data from a room for a user that has never been in it. "
  142. "This should not have happened."
  143. )
  144. raise UnstableSpecAuthError(
  145. 403,
  146. "User not in room",
  147. errcode=Codes.NOT_JOINED,
  148. )
  149. return data
  150. async def get_state_events(
  151. self,
  152. requester: Requester,
  153. room_id: str,
  154. state_filter: Optional[StateFilter] = None,
  155. at_token: Optional[StreamToken] = None,
  156. ) -> List[dict]:
  157. """Retrieve all state events for a given room. If the user is
  158. joined to the room then return the current state. If the user has
  159. left the room return the state events from when they left. If an explicit
  160. 'at' parameter is passed, return the state events as of that event, if
  161. visible.
  162. Args:
  163. requester: The user requesting state events.
  164. room_id: The room ID to get all state events from.
  165. state_filter: The state filter used to fetch state from the database.
  166. at_token: the stream token of the at which we are requesting
  167. the stats. If the user is not allowed to view the state as of that
  168. stream token, we raise a 403 SynapseError. If None, returns the current
  169. state based on the current_state_events table.
  170. Returns:
  171. A list of dicts representing state events. [{}, {}, {}]
  172. Raises:
  173. NotFoundError (404) if the at token does not yield an event
  174. AuthError (403) if the user doesn't have permission to view
  175. members of this room.
  176. """
  177. state_filter = state_filter or StateFilter.all()
  178. user_id = requester.user.to_string()
  179. if at_token:
  180. last_event_id = (
  181. await self.store.get_last_event_in_room_before_stream_ordering(
  182. room_id,
  183. end_token=at_token.room_key,
  184. )
  185. )
  186. if not last_event_id:
  187. raise NotFoundError("Can't find event for token %s" % (at_token,))
  188. if not await self._user_can_see_state_at_event(
  189. user_id, room_id, last_event_id
  190. ):
  191. raise AuthError(
  192. 403,
  193. "User %s not allowed to view events in room %s at token %s"
  194. % (user_id, room_id, at_token),
  195. )
  196. room_state_events = (
  197. await self._state_storage_controller.get_state_for_events(
  198. [last_event_id], state_filter=state_filter
  199. )
  200. )
  201. room_state: Mapping[Any, EventBase] = room_state_events[last_event_id]
  202. else:
  203. (
  204. membership,
  205. membership_event_id,
  206. ) = await self.auth.check_user_in_room_or_world_readable(
  207. room_id, requester, allow_departed_users=True
  208. )
  209. if membership == Membership.JOIN:
  210. state_ids = await self._state_storage_controller.get_current_state_ids(
  211. room_id, state_filter=state_filter
  212. )
  213. room_state = await self.store.get_events(state_ids.values())
  214. elif membership == Membership.LEAVE:
  215. # If the membership is not JOIN, then the event ID should exist.
  216. assert (
  217. membership_event_id is not None
  218. ), "check_user_in_room_or_world_readable returned invalid data"
  219. room_state_events = (
  220. await self._state_storage_controller.get_state_for_events(
  221. [membership_event_id], state_filter=state_filter
  222. )
  223. )
  224. room_state = room_state_events[membership_event_id]
  225. events = self._event_serializer.serialize_events(
  226. room_state.values(),
  227. self.clock.time_msec(),
  228. config=SerializeEventConfig(requester=requester),
  229. )
  230. return events
  231. async def _user_can_see_state_at_event(
  232. self, user_id: str, room_id: str, event_id: str
  233. ) -> bool:
  234. # check whether the user was in the room, and the history visibility,
  235. # at that time.
  236. state_map = await self._state_storage_controller.get_state_for_event(
  237. event_id,
  238. StateFilter.from_types(
  239. [
  240. (EventTypes.Member, user_id),
  241. (EventTypes.RoomHistoryVisibility, ""),
  242. ]
  243. ),
  244. )
  245. membership = None
  246. membership_event = state_map.get((EventTypes.Member, user_id))
  247. if membership_event:
  248. membership = membership_event.membership
  249. # if the user was a member of the room at the time of the event,
  250. # they can see it.
  251. if membership == Membership.JOIN:
  252. return True
  253. # otherwise, it depends on the history visibility.
  254. visibility = get_effective_room_visibility_from_state(state_map)
  255. if visibility == HistoryVisibility.JOINED:
  256. # we weren't a member at the time of the event, so we can't see this event.
  257. return False
  258. # otherwise *invited* is good enough
  259. if membership == Membership.INVITE:
  260. return True
  261. if visibility == HistoryVisibility.INVITED:
  262. # we weren't invited, so we can't see this event.
  263. return False
  264. if visibility == HistoryVisibility.WORLD_READABLE:
  265. return True
  266. # So it's SHARED, and the user was not a member at the time. The user cannot
  267. # see history, unless they have *subsequently* joined the room.
  268. #
  269. # XXX: if the user has subsequently joined and then left again,
  270. # ideally we would share history up to the point they left. But
  271. # we don't know when they left. We just treat it as though they
  272. # never joined, and restrict access.
  273. (
  274. current_membership,
  275. _,
  276. ) = await self.store.get_local_current_membership_for_user_in_room(
  277. user_id, event_id
  278. )
  279. return current_membership == Membership.JOIN
  280. async def get_joined_members(self, requester: Requester, room_id: str) -> dict:
  281. """Get all the joined members in the room and their profile information.
  282. If the user has left the room return the state events from when they left.
  283. Args:
  284. requester: The user requesting state events.
  285. room_id: The room ID to get all state events from.
  286. Returns:
  287. A dict of user_id to profile info
  288. """
  289. if not requester.app_service:
  290. # We check AS auth after fetching the room membership, as it
  291. # requires us to pull out all joined members anyway.
  292. membership, _ = await self.auth.check_user_in_room_or_world_readable(
  293. room_id, requester, allow_departed_users=True
  294. )
  295. if membership != Membership.JOIN:
  296. raise SynapseError(
  297. code=403,
  298. errcode=Codes.FORBIDDEN,
  299. msg="Getting joined members while not being a current member of the room is forbidden.",
  300. )
  301. users_with_profile = (
  302. await self._state_storage_controller.get_users_in_room_with_profiles(
  303. room_id
  304. )
  305. )
  306. # If this is an AS, double check that they are allowed to see the members.
  307. # This can either be because the AS user is in the room or because there
  308. # is a user in the room that the AS is "interested in"
  309. if (
  310. requester.app_service
  311. and requester.user.to_string() not in users_with_profile
  312. ):
  313. for uid in users_with_profile:
  314. if requester.app_service.is_interested_in_user(uid):
  315. break
  316. else:
  317. # Loop fell through, AS has no interested users in room
  318. raise UnstableSpecAuthError(
  319. 403,
  320. "Appservice not in room",
  321. errcode=Codes.NOT_JOINED,
  322. )
  323. return {
  324. user_id: {
  325. "avatar_url": profile.avatar_url,
  326. "display_name": profile.display_name,
  327. }
  328. for user_id, profile in users_with_profile.items()
  329. }
  330. def maybe_schedule_expiry(self, event: EventBase) -> None:
  331. """Schedule the expiry of an event if there's not already one scheduled,
  332. or if the one running is for an event that will expire after the provided
  333. timestamp.
  334. This function needs to invalidate the event cache, which is only possible on
  335. the master process, and therefore needs to be run on there.
  336. Args:
  337. event: The event to schedule the expiry of.
  338. """
  339. expiry_ts = event.content.get(EventContentFields.SELF_DESTRUCT_AFTER)
  340. if type(expiry_ts) is not int or event.is_state():
  341. return
  342. # _schedule_expiry_for_event won't actually schedule anything if there's already
  343. # a task scheduled for a timestamp that's sooner than the provided one.
  344. self._schedule_expiry_for_event(event.event_id, expiry_ts)
  345. async def _schedule_next_expiry(self) -> None:
  346. """Retrieve the ID and the expiry timestamp of the next event to be expired,
  347. and schedule an expiry task for it.
  348. If there's no event left to expire, set _expiry_scheduled to None so that a
  349. future call to save_expiry_ts can schedule a new expiry task.
  350. """
  351. # Try to get the expiry timestamp of the next event to expire.
  352. res = await self.store.get_next_event_to_expire()
  353. if res:
  354. event_id, expiry_ts = res
  355. self._schedule_expiry_for_event(event_id, expiry_ts)
  356. def _schedule_expiry_for_event(self, event_id: str, expiry_ts: int) -> None:
  357. """Schedule an expiry task for the provided event if there's not already one
  358. scheduled at a timestamp that's sooner than the provided one.
  359. Args:
  360. event_id: The ID of the event to expire.
  361. expiry_ts: The timestamp at which to expire the event.
  362. """
  363. if self._scheduled_expiry:
  364. # If the provided timestamp refers to a time before the scheduled time of the
  365. # next expiry task, cancel that task and reschedule it for this timestamp.
  366. next_scheduled_expiry_ts = self._scheduled_expiry.getTime() * 1000
  367. if expiry_ts < next_scheduled_expiry_ts:
  368. self._scheduled_expiry.cancel()
  369. else:
  370. return
  371. # Figure out how many seconds we need to wait before expiring the event.
  372. now_ms = self.clock.time_msec()
  373. delay = (expiry_ts - now_ms) / 1000
  374. # callLater doesn't support negative delays, so trim the delay to 0 if we're
  375. # in that case.
  376. if delay < 0:
  377. delay = 0
  378. logger.info("Scheduling expiry for event %s in %.3fs", event_id, delay)
  379. self._scheduled_expiry = self.clock.call_later(
  380. delay,
  381. run_as_background_process,
  382. "_expire_event",
  383. self._expire_event,
  384. event_id,
  385. )
  386. async def _expire_event(self, event_id: str) -> None:
  387. """Retrieve and expire an event that needs to be expired from the database.
  388. If the event doesn't exist in the database, log it and delete the expiry date
  389. from the database (so that we don't try to expire it again).
  390. """
  391. assert self._ephemeral_events_enabled
  392. self._scheduled_expiry = None
  393. logger.info("Expiring event %s", event_id)
  394. try:
  395. # Expire the event if we know about it. This function also deletes the expiry
  396. # date from the database in the same database transaction.
  397. await self.store.expire_event(event_id)
  398. except Exception as e:
  399. logger.error("Could not expire event %s: %r", event_id, e)
  400. # Schedule the expiry of the next event to expire.
  401. await self._schedule_next_expiry()
  402. # The duration (in ms) after which rooms should be removed
  403. # `_rooms_to_exclude_from_dummy_event_insertion` (with the effect that we will try
  404. # to generate a dummy event for them once more)
  405. #
  406. _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY = 7 * 24 * 60 * 60 * 1000
  407. class EventCreationHandler:
  408. def __init__(self, hs: "HomeServer"):
  409. self.hs = hs
  410. self.auth_blocking = hs.get_auth_blocking()
  411. self._event_auth_handler = hs.get_event_auth_handler()
  412. self.store = hs.get_datastores().main
  413. self._storage_controllers = hs.get_storage_controllers()
  414. self.state = hs.get_state_handler()
  415. self.clock = hs.get_clock()
  416. self.validator = EventValidator()
  417. self.profile_handler = hs.get_profile_handler()
  418. self.event_builder_factory = hs.get_event_builder_factory()
  419. self.server_name = hs.hostname
  420. self.notifier = hs.get_notifier()
  421. self.config = hs.config
  422. self.require_membership_for_aliases = (
  423. hs.config.server.require_membership_for_aliases
  424. )
  425. self._events_shard_config = self.config.worker.events_shard_config
  426. self._instance_name = hs.get_instance_name()
  427. self._notifier = hs.get_notifier()
  428. self.room_prejoin_state_types = self.hs.config.api.room_prejoin_state
  429. self.membership_types_to_include_profile_data_in = {
  430. Membership.JOIN,
  431. Membership.KNOCK,
  432. }
  433. if self.hs.config.server.include_profile_data_on_invite:
  434. self.membership_types_to_include_profile_data_in.add(Membership.INVITE)
  435. self.send_event = ReplicationSendEventRestServlet.make_client(hs)
  436. self.send_events = ReplicationSendEventsRestServlet.make_client(hs)
  437. self.request_ratelimiter = hs.get_request_ratelimiter()
  438. # We limit concurrent event creation for a room to 1. This prevents state resolution
  439. # from occurring when sending bursts of events to a local room
  440. self.limiter = Linearizer(max_count=1, name="room_event_creation_limit")
  441. self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()
  442. self.spam_checker = hs.get_spam_checker()
  443. self.third_party_event_rules: "ThirdPartyEventRules" = (
  444. self.hs.get_third_party_event_rules()
  445. )
  446. self._block_events_without_consent_error = (
  447. self.config.consent.block_events_without_consent_error
  448. )
  449. # we need to construct a ConsentURIBuilder here, as it checks that the necessary
  450. # config options, but *only* if we have a configuration for which we are
  451. # going to need it.
  452. if self._block_events_without_consent_error:
  453. self._consent_uri_builder = ConsentURIBuilder(self.config)
  454. # Rooms which should be excluded from dummy insertion. (For instance,
  455. # those without local users who can send events into the room).
  456. #
  457. # map from room id to time-of-last-attempt.
  458. #
  459. self._rooms_to_exclude_from_dummy_event_insertion: Dict[str, int] = {}
  460. # The number of forward extremeities before a dummy event is sent.
  461. self._dummy_events_threshold = hs.config.server.dummy_events_threshold
  462. if (
  463. self.config.worker.run_background_tasks
  464. and self.config.server.cleanup_extremities_with_dummy_events
  465. ):
  466. self.clock.looping_call(
  467. lambda: run_as_background_process(
  468. "send_dummy_events_to_fill_extremities",
  469. self._send_dummy_events_to_fill_extremities,
  470. ),
  471. 5 * 60 * 1000,
  472. )
  473. self._message_handler = hs.get_message_handler()
  474. self._ephemeral_events_enabled = hs.config.server.enable_ephemeral_messages
  475. self._external_cache = hs.get_external_cache()
  476. # Stores the state groups we've recently added to the joined hosts
  477. # external cache. Note that the timeout must be significantly less than
  478. # the TTL on the external cache.
  479. self._external_cache_joined_hosts_updates: Optional[ExpiringCache] = None
  480. if self._external_cache.is_enabled():
  481. self._external_cache_joined_hosts_updates = ExpiringCache(
  482. "_external_cache_joined_hosts_updates",
  483. self.clock,
  484. expiry_ms=30 * 60 * 1000,
  485. )
  486. async def create_event(
  487. self,
  488. requester: Requester,
  489. event_dict: dict,
  490. txn_id: Optional[str] = None,
  491. allow_no_prev_events: bool = False,
  492. prev_event_ids: Optional[List[str]] = None,
  493. auth_event_ids: Optional[List[str]] = None,
  494. state_event_ids: Optional[List[str]] = None,
  495. require_consent: bool = True,
  496. outlier: bool = False,
  497. historical: bool = False,
  498. depth: Optional[int] = None,
  499. state_map: Optional[StateMap[str]] = None,
  500. for_batch: bool = False,
  501. current_state_group: Optional[int] = None,
  502. ) -> Tuple[EventBase, UnpersistedEventContextBase]:
  503. """
  504. Given a dict from a client, create a new event. If bool for_batch is true, will
  505. create an event using the prev_event_ids, and will create an event context for
  506. the event using the parameters state_map and current_state_group, thus these parameters
  507. must be provided in this case if for_batch is True. The subsequently created event
  508. and context are suitable for being batched up and bulk persisted to the database
  509. with other similarly created events.
  510. Creates an FrozenEvent object, filling out auth_events, prev_events,
  511. etc.
  512. Adds display names to Join membership events.
  513. Args:
  514. requester
  515. event_dict: An entire event
  516. txn_id
  517. allow_no_prev_events: Whether to allow this event to be created an empty
  518. list of prev_events. Normally this is prohibited just because most
  519. events should have a prev_event and we should only use this in special
  520. cases like MSC2716.
  521. prev_event_ids:
  522. the forward extremities to use as the prev_events for the
  523. new event.
  524. If None, they will be requested from the database.
  525. auth_event_ids:
  526. The event ids to use as the auth_events for the new event.
  527. Should normally be left as None, which will cause them to be calculated
  528. based on the room state at the prev_events.
  529. If non-None, prev_event_ids must also be provided.
  530. state_event_ids:
  531. The full state at a given event. This is used particularly by the MSC2716
  532. /batch_send endpoint. One use case is with insertion events which float at
  533. the beginning of a historical batch and don't have any `prev_events` to
  534. derive from; we add all of these state events as the explicit state so the
  535. rest of the historical batch can inherit the same state and state_group.
  536. This should normally be left as None, which will cause the auth_event_ids
  537. to be calculated based on the room state at the prev_events.
  538. require_consent: Whether to check if the requester has
  539. consented to the privacy policy.
  540. outlier: Indicates whether the event is an `outlier`, i.e. if
  541. it's from an arbitrary point and floating in the DAG as
  542. opposed to being inline with the current DAG.
  543. historical: Indicates whether the message is being inserted
  544. back in time around some existing events. This is used to skip
  545. a few checks and mark the event as backfilled.
  546. depth: Override the depth used to order the event in the DAG.
  547. Should normally be set to None, which will cause the depth to be calculated
  548. based on the prev_events.
  549. state_map: A state map of previously created events, used only when creating events
  550. for batch persisting
  551. for_batch: whether the event is being created for batch persisting to the db
  552. current_state_group: the current state group, used only for creating events for
  553. batch persisting
  554. Raises:
  555. ResourceLimitError if server is blocked to some resource being
  556. exceeded
  557. Returns:
  558. Tuple of created event, Context
  559. """
  560. await self.auth_blocking.check_auth_blocking(requester=requester)
  561. if event_dict["type"] == EventTypes.Create and event_dict["state_key"] == "":
  562. room_version_id = event_dict["content"]["room_version"]
  563. maybe_room_version_obj = KNOWN_ROOM_VERSIONS.get(room_version_id)
  564. if not maybe_room_version_obj:
  565. # this can happen if support is withdrawn for a room version
  566. raise UnsupportedRoomVersionError(room_version_id)
  567. room_version_obj = maybe_room_version_obj
  568. else:
  569. try:
  570. room_version_obj = await self.store.get_room_version(
  571. event_dict["room_id"]
  572. )
  573. except NotFoundError:
  574. raise AuthError(403, "Unknown room")
  575. builder = self.event_builder_factory.for_room_version(
  576. room_version_obj, event_dict
  577. )
  578. self.validator.validate_builder(builder)
  579. if builder.type == EventTypes.Member:
  580. membership = builder.content.get("membership", None)
  581. target = UserID.from_string(builder.state_key)
  582. if membership in self.membership_types_to_include_profile_data_in:
  583. # If event doesn't include a display name, add one.
  584. profile = self.profile_handler
  585. content = builder.content
  586. try:
  587. if "displayname" not in content:
  588. displayname = await profile.get_displayname(target)
  589. if displayname is not None:
  590. content["displayname"] = displayname
  591. if "avatar_url" not in content:
  592. avatar_url = await profile.get_avatar_url(target)
  593. if avatar_url is not None:
  594. content["avatar_url"] = avatar_url
  595. except Exception as e:
  596. logger.info(
  597. "Failed to get profile information for %r: %s", target, e
  598. )
  599. is_exempt = await self._is_exempt_from_privacy_policy(builder, requester)
  600. if require_consent and not is_exempt:
  601. await self.assert_accepted_privacy_policy(requester)
  602. if requester.access_token_id is not None:
  603. builder.internal_metadata.token_id = requester.access_token_id
  604. if txn_id is not None:
  605. builder.internal_metadata.txn_id = txn_id
  606. builder.internal_metadata.outlier = outlier
  607. builder.internal_metadata.historical = historical
  608. event, unpersisted_context = await self.create_new_client_event(
  609. builder=builder,
  610. requester=requester,
  611. allow_no_prev_events=allow_no_prev_events,
  612. prev_event_ids=prev_event_ids,
  613. auth_event_ids=auth_event_ids,
  614. state_event_ids=state_event_ids,
  615. depth=depth,
  616. state_map=state_map,
  617. for_batch=for_batch,
  618. current_state_group=current_state_group,
  619. )
  620. # In an ideal world we wouldn't need the second part of this condition. However,
  621. # this behaviour isn't spec'd yet, meaning we should be able to deactivate this
  622. # behaviour. Another reason is that this code is also evaluated each time a new
  623. # m.room.aliases event is created, which includes hitting a /directory route.
  624. # Therefore not including this condition here would render the similar one in
  625. # synapse.handlers.directory pointless.
  626. if builder.type == EventTypes.Aliases and self.require_membership_for_aliases:
  627. # Ideally we'd do the membership check in event_auth.check(), which
  628. # describes a spec'd algorithm for authenticating events received over
  629. # federation as well as those created locally. As of room v3, aliases events
  630. # can be created by users that are not in the room, therefore we have to
  631. # tolerate them in event_auth.check().
  632. if for_batch:
  633. assert state_map is not None
  634. prev_event_id = state_map.get((EventTypes.Member, event.sender))
  635. else:
  636. prev_state_ids = await unpersisted_context.get_prev_state_ids(
  637. StateFilter.from_types([(EventTypes.Member, None)])
  638. )
  639. prev_event_id = prev_state_ids.get((EventTypes.Member, event.sender))
  640. prev_event = (
  641. await self.store.get_event(prev_event_id, allow_none=True)
  642. if prev_event_id
  643. else None
  644. )
  645. if not prev_event or prev_event.membership != Membership.JOIN:
  646. logger.warning(
  647. (
  648. "Attempt to send `m.room.aliases` in room %s by user %s but"
  649. " membership is %s"
  650. ),
  651. event.room_id,
  652. event.sender,
  653. prev_event.membership if prev_event else None,
  654. )
  655. raise AuthError(
  656. 403, "You must be in the room to create an alias for it"
  657. )
  658. self.validator.validate_new(event, self.config)
  659. return event, unpersisted_context
  660. async def _is_exempt_from_privacy_policy(
  661. self, builder: EventBuilder, requester: Requester
  662. ) -> bool:
  663. """ "Determine if an event to be sent is exempt from having to consent
  664. to the privacy policy
  665. Args:
  666. builder: event being created
  667. requester: user requesting this event
  668. Returns:
  669. true if the event can be sent without the user consenting
  670. """
  671. # the only thing the user can do is join the server notices room.
  672. if builder.type == EventTypes.Member:
  673. membership = builder.content.get("membership", None)
  674. if membership == Membership.JOIN:
  675. return await self.store.is_server_notice_room(builder.room_id)
  676. elif membership == Membership.LEAVE:
  677. # the user is always allowed to leave (but not kick people)
  678. return builder.state_key == requester.user.to_string()
  679. return False
  680. async def assert_accepted_privacy_policy(self, requester: Requester) -> None:
  681. """Check if a user has accepted the privacy policy
  682. Called when the given user is about to do something that requires
  683. privacy consent. We see if the user is exempt and otherwise check that
  684. they have given consent. If they have not, a ConsentNotGiven error is
  685. raised.
  686. Args:
  687. requester: The user making the request
  688. Returns:
  689. Returns normally if the user has consented or is exempt
  690. Raises:
  691. ConsentNotGivenError: if the user has not given consent yet
  692. """
  693. if self._block_events_without_consent_error is None:
  694. return
  695. # exempt AS users from needing consent
  696. if requester.app_service is not None:
  697. return
  698. user_id = requester.authenticated_entity
  699. if not user_id.startswith("@"):
  700. # The authenticated entity might not be a user, e.g. if it's the
  701. # server puppetting the user.
  702. return
  703. user = UserID.from_string(user_id)
  704. # exempt the system notices user
  705. if (
  706. self.config.servernotices.server_notices_mxid is not None
  707. and user_id == self.config.servernotices.server_notices_mxid
  708. ):
  709. return
  710. u = await self.store.get_user_by_id(user_id)
  711. assert u is not None
  712. if u["user_type"] in (UserTypes.SUPPORT, UserTypes.BOT):
  713. # support and bot users are not required to consent
  714. return
  715. if u["appservice_id"] is not None:
  716. # users registered by an appservice are exempt
  717. return
  718. if u["consent_version"] == self.config.consent.user_consent_version:
  719. return
  720. consent_uri = self._consent_uri_builder.build_user_consent_uri(user.localpart)
  721. msg = self._block_events_without_consent_error % {"consent_uri": consent_uri}
  722. raise ConsentNotGivenError(msg=msg, consent_uri=consent_uri)
  723. async def deduplicate_state_event(
  724. self, event: EventBase, context: EventContext
  725. ) -> Optional[EventBase]:
  726. """
  727. Checks whether event is in the latest resolved state in context.
  728. Args:
  729. event: The event to check for duplication.
  730. context: The event context.
  731. Returns:
  732. The previous version of the event is returned, if it is found in the
  733. event context. Otherwise, None is returned.
  734. """
  735. if event.internal_metadata.is_outlier():
  736. # This can happen due to out of band memberships
  737. return None
  738. prev_state_ids = await context.get_prev_state_ids(
  739. StateFilter.from_types([(event.type, None)])
  740. )
  741. prev_event_id = prev_state_ids.get((event.type, event.state_key))
  742. if not prev_event_id:
  743. return None
  744. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  745. if not prev_event:
  746. return None
  747. if prev_event and event.user_id == prev_event.user_id:
  748. prev_content = encode_canonical_json(prev_event.content)
  749. next_content = encode_canonical_json(event.content)
  750. if prev_content == next_content:
  751. return prev_event
  752. return None
  753. async def get_event_from_transaction(
  754. self,
  755. requester: Requester,
  756. txn_id: str,
  757. room_id: str,
  758. ) -> Optional[EventBase]:
  759. """For the given transaction ID and room ID, check if there is a matching event.
  760. If so, fetch it and return it.
  761. Args:
  762. requester: The requester making the request in the context of which we want
  763. to fetch the event.
  764. txn_id: The transaction ID.
  765. room_id: The room ID.
  766. Returns:
  767. An event if one could be found, None otherwise.
  768. """
  769. if requester.access_token_id:
  770. existing_event_id = await self.store.get_event_id_from_transaction_id(
  771. room_id,
  772. requester.user.to_string(),
  773. requester.access_token_id,
  774. txn_id,
  775. )
  776. if existing_event_id:
  777. return await self.store.get_event(existing_event_id)
  778. return None
  779. async def create_and_send_nonmember_event(
  780. self,
  781. requester: Requester,
  782. event_dict: dict,
  783. allow_no_prev_events: bool = False,
  784. prev_event_ids: Optional[List[str]] = None,
  785. state_event_ids: Optional[List[str]] = None,
  786. ratelimit: bool = True,
  787. txn_id: Optional[str] = None,
  788. ignore_shadow_ban: bool = False,
  789. outlier: bool = False,
  790. historical: bool = False,
  791. depth: Optional[int] = None,
  792. ) -> Tuple[EventBase, int]:
  793. """
  794. Creates an event, then sends it.
  795. See self.create_event and self.handle_new_client_event.
  796. Args:
  797. requester: The requester sending the event.
  798. event_dict: An entire event.
  799. allow_no_prev_events: Whether to allow this event to be created an empty
  800. list of prev_events. Normally this is prohibited just because most
  801. events should have a prev_event and we should only use this in special
  802. cases like MSC2716.
  803. prev_event_ids:
  804. The event IDs to use as the prev events.
  805. Should normally be left as None to automatically request them
  806. from the database.
  807. state_event_ids:
  808. The full state at a given event. This is used particularly by the MSC2716
  809. /batch_send endpoint. One use case is with insertion events which float at
  810. the beginning of a historical batch and don't have any `prev_events` to
  811. derive from; we add all of these state events as the explicit state so the
  812. rest of the historical batch can inherit the same state and state_group.
  813. This should normally be left as None, which will cause the auth_event_ids
  814. to be calculated based on the room state at the prev_events.
  815. ratelimit: Whether to rate limit this send.
  816. txn_id: The transaction ID.
  817. ignore_shadow_ban: True if shadow-banned users should be allowed to
  818. send this event.
  819. outlier: Indicates whether the event is an `outlier`, i.e. if
  820. it's from an arbitrary point and floating in the DAG as
  821. opposed to being inline with the current DAG.
  822. historical: Indicates whether the message is being inserted
  823. back in time around some existing events. This is used to skip
  824. a few checks and mark the event as backfilled.
  825. depth: Override the depth used to order the event in the DAG.
  826. Should normally be set to None, which will cause the depth to be calculated
  827. based on the prev_events.
  828. Returns:
  829. The event, and its stream ordering (if deduplication happened,
  830. the previous, duplicate event).
  831. Raises:
  832. ShadowBanError if the requester has been shadow-banned.
  833. """
  834. if event_dict["type"] == EventTypes.Member:
  835. raise SynapseError(
  836. 500, "Tried to send member event through non-member codepath"
  837. )
  838. if not ignore_shadow_ban and requester.shadow_banned:
  839. # We randomly sleep a bit just to annoy the requester.
  840. await self.clock.sleep(random.randint(1, 10))
  841. raise ShadowBanError()
  842. if ratelimit:
  843. await self.request_ratelimiter.ratelimit(requester, update=False)
  844. # We limit the number of concurrent event sends in a room so that we
  845. # don't fork the DAG too much. If we don't limit then we can end up in
  846. # a situation where event persistence can't keep up, causing
  847. # extremities to pile up, which in turn leads to state resolution
  848. # taking longer.
  849. async with self.limiter.queue(event_dict["room_id"]):
  850. if txn_id:
  851. event = await self.get_event_from_transaction(
  852. requester, txn_id, event_dict["room_id"]
  853. )
  854. if event:
  855. # we know it was persisted, so must have a stream ordering
  856. assert event.internal_metadata.stream_ordering
  857. return (
  858. event,
  859. event.internal_metadata.stream_ordering,
  860. )
  861. # Try several times, it could fail with PartialStateConflictError
  862. # in handle_new_client_event, cf comment in except block.
  863. max_retries = 5
  864. for i in range(max_retries):
  865. try:
  866. event, unpersisted_context = await self.create_event(
  867. requester,
  868. event_dict,
  869. txn_id=txn_id,
  870. allow_no_prev_events=allow_no_prev_events,
  871. prev_event_ids=prev_event_ids,
  872. state_event_ids=state_event_ids,
  873. outlier=outlier,
  874. historical=historical,
  875. depth=depth,
  876. )
  877. context = await unpersisted_context.persist(event)
  878. assert self.hs.is_mine_id(event.sender), "User must be our own: %s" % (
  879. event.sender,
  880. )
  881. spam_check_result = await self.spam_checker.check_event_for_spam(event)
  882. if spam_check_result != self.spam_checker.NOT_SPAM:
  883. if isinstance(spam_check_result, tuple):
  884. try:
  885. [code, dict] = spam_check_result
  886. raise SynapseError(
  887. 403,
  888. "This message had been rejected as probable spam",
  889. code,
  890. dict,
  891. )
  892. except ValueError:
  893. logger.error(
  894. "Spam-check module returned invalid error value. Expecting [code, dict], got %s",
  895. spam_check_result,
  896. )
  897. raise SynapseError(
  898. 403,
  899. "This message has been rejected as probable spam",
  900. Codes.FORBIDDEN,
  901. )
  902. # Backwards compatibility: if the return value is not an error code, it
  903. # means the module returned an error message to be included in the
  904. # SynapseError (which is now deprecated).
  905. raise SynapseError(
  906. 403,
  907. spam_check_result,
  908. Codes.FORBIDDEN,
  909. )
  910. ev = await self.handle_new_client_event(
  911. requester=requester,
  912. events_and_context=[(event, context)],
  913. ratelimit=ratelimit,
  914. ignore_shadow_ban=ignore_shadow_ban,
  915. )
  916. break
  917. except PartialStateConflictError as e:
  918. # Persisting couldn't happen because the room got un-partial stated
  919. # in the meantime and context needs to be recomputed, so let's do so.
  920. if i == max_retries - 1:
  921. raise e
  922. pass
  923. # we know it was persisted, so must have a stream ordering
  924. assert ev.internal_metadata.stream_ordering
  925. return ev, ev.internal_metadata.stream_ordering
  926. @measure_func("create_new_client_event")
  927. async def create_new_client_event(
  928. self,
  929. builder: EventBuilder,
  930. requester: Optional[Requester] = None,
  931. allow_no_prev_events: bool = False,
  932. prev_event_ids: Optional[List[str]] = None,
  933. auth_event_ids: Optional[List[str]] = None,
  934. state_event_ids: Optional[List[str]] = None,
  935. depth: Optional[int] = None,
  936. state_map: Optional[StateMap[str]] = None,
  937. for_batch: bool = False,
  938. current_state_group: Optional[int] = None,
  939. ) -> Tuple[EventBase, UnpersistedEventContextBase]:
  940. """Create a new event for a local client. If bool for_batch is true, will
  941. create an event using the prev_event_ids, and will create an event context for
  942. the event using the parameters state_map and current_state_group, thus these parameters
  943. must be provided in this case if for_batch is True. The subsequently created event
  944. and context are suitable for being batched up and bulk persisted to the database
  945. with other similarly created events. Note that this returns an UnpersistedEventContext,
  946. which must be converted to an EventContext before it can be sent to the DB.
  947. Args:
  948. builder:
  949. requester:
  950. allow_no_prev_events: Whether to allow this event to be created an empty
  951. list of prev_events. Normally this is prohibited just because most
  952. events should have a prev_event and we should only use this in special
  953. cases like MSC2716.
  954. prev_event_ids:
  955. the forward extremities to use as the prev_events for the
  956. new event.
  957. If None, they will be requested from the database.
  958. auth_event_ids:
  959. The event ids to use as the auth_events for the new event.
  960. Should normally be left as None, which will cause them to be calculated
  961. based on the room state at the prev_events.
  962. state_event_ids:
  963. The full state at a given event. This is used particularly by the MSC2716
  964. /batch_send endpoint. One use case is with insertion events which float at
  965. the beginning of a historical batch and don't have any `prev_events` to
  966. derive from; we add all of these state events as the explicit state so the
  967. rest of the historical batch can inherit the same state and state_group.
  968. This should normally be left as None, which will cause the auth_event_ids
  969. to be calculated based on the room state at the prev_events.
  970. depth: Override the depth used to order the event in the DAG.
  971. Should normally be set to None, which will cause the depth to be calculated
  972. based on the prev_events.
  973. state_map: A state map of previously created events, used only when creating events
  974. for batch persisting
  975. for_batch: whether the event is being created for batch persisting to the db
  976. current_state_group: the current state group, used only for creating events for
  977. batch persisting
  978. Returns:
  979. Tuple of created event, UnpersistedEventContext
  980. """
  981. # Strip down the state_event_ids to only what we need to auth the event.
  982. # For example, we don't need extra m.room.member that don't match event.sender
  983. if state_event_ids is not None:
  984. # Do a quick check to make sure that prev_event_ids is present to
  985. # make the type-checking around `builder.build` happy.
  986. # prev_event_ids could be an empty array though.
  987. assert prev_event_ids is not None
  988. temp_event = await builder.build(
  989. prev_event_ids=prev_event_ids,
  990. auth_event_ids=state_event_ids,
  991. depth=depth,
  992. )
  993. state_events = await self.store.get_events_as_list(state_event_ids)
  994. # Create a StateMap[str]
  995. current_state_ids = {
  996. (e.type, e.state_key): e.event_id for e in state_events
  997. }
  998. # Actually strip down and only use the necessary auth events
  999. auth_event_ids = self._event_auth_handler.compute_auth_events(
  1000. event=temp_event,
  1001. current_state_ids=current_state_ids,
  1002. for_verification=False,
  1003. )
  1004. if prev_event_ids is not None:
  1005. assert (
  1006. len(prev_event_ids) <= 10
  1007. ), "Attempting to create an event with %i prev_events" % (
  1008. len(prev_event_ids),
  1009. )
  1010. else:
  1011. prev_event_ids = await self.store.get_prev_events_for_room(builder.room_id)
  1012. # Do a quick sanity check here, rather than waiting until we've created the
  1013. # event and then try to auth it (which fails with a somewhat confusing "No
  1014. # create event in auth events")
  1015. if allow_no_prev_events:
  1016. # We allow events with no `prev_events` but it better have some `auth_events`
  1017. assert (
  1018. builder.type == EventTypes.Create
  1019. # Allow an event to have empty list of prev_event_ids
  1020. # only if it has auth_event_ids.
  1021. or auth_event_ids
  1022. ), "Attempting to create a non-m.room.create event with no prev_events or auth_event_ids"
  1023. else:
  1024. # we now ought to have some prev_events (unless it's a create event).
  1025. assert (
  1026. builder.type == EventTypes.Create or prev_event_ids
  1027. ), "Attempting to create a non-m.room.create event with no prev_events"
  1028. if for_batch:
  1029. assert prev_event_ids is not None
  1030. assert state_map is not None
  1031. auth_ids = self._event_auth_handler.compute_auth_events(builder, state_map)
  1032. event = await builder.build(
  1033. prev_event_ids=prev_event_ids, auth_event_ids=auth_ids, depth=depth
  1034. )
  1035. context: UnpersistedEventContextBase = (
  1036. await self.state.calculate_context_info(
  1037. event,
  1038. state_ids_before_event=state_map,
  1039. partial_state=False,
  1040. state_group_before_event=current_state_group,
  1041. )
  1042. )
  1043. else:
  1044. event = await builder.build(
  1045. prev_event_ids=prev_event_ids,
  1046. auth_event_ids=auth_event_ids,
  1047. depth=depth,
  1048. )
  1049. # Pass on the outlier property from the builder to the event
  1050. # after it is created
  1051. if builder.internal_metadata.outlier:
  1052. event.internal_metadata.outlier = True
  1053. context = EventContext.for_outlier(self._storage_controllers)
  1054. elif (
  1055. event.type == EventTypes.MSC2716_INSERTION
  1056. and state_event_ids
  1057. and builder.internal_metadata.is_historical()
  1058. ):
  1059. # Add explicit state to the insertion event so it has state to derive
  1060. # from even though it's floating with no `prev_events`. The rest of
  1061. # the batch can derive from this state and state_group.
  1062. #
  1063. # TODO(faster_joins): figure out how this works, and make sure that the
  1064. # old state is complete.
  1065. # https://github.com/matrix-org/synapse/issues/13003
  1066. metadata = await self.store.get_metadata_for_events(state_event_ids)
  1067. state_map_for_event: MutableStateMap[str] = {}
  1068. for state_id in state_event_ids:
  1069. data = metadata.get(state_id)
  1070. if data is None:
  1071. # We're trying to persist a new historical batch of events
  1072. # with the given state, e.g. via
  1073. # `RoomBatchSendEventRestServlet`. The state can be inferred
  1074. # by Synapse or set directly by the client.
  1075. #
  1076. # Either way, we should have persisted all the state before
  1077. # getting here.
  1078. raise Exception(
  1079. f"State event {state_id} not found in DB,"
  1080. " Synapse should have persisted it before using it."
  1081. )
  1082. if data.state_key is None:
  1083. raise Exception(
  1084. f"Trying to set non-state event {state_id} as state"
  1085. )
  1086. state_map_for_event[(data.event_type, data.state_key)] = state_id
  1087. # TODO(faster_joins): check how MSC2716 works and whether we can have
  1088. # partial state here
  1089. # https://github.com/matrix-org/synapse/issues/13003
  1090. context = await self.state.calculate_context_info(
  1091. event,
  1092. state_ids_before_event=state_map_for_event,
  1093. partial_state=False,
  1094. )
  1095. else:
  1096. context = await self.state.calculate_context_info(event)
  1097. if requester:
  1098. context.app_service = requester.app_service
  1099. res, new_content = await self.third_party_event_rules.check_event_allowed(
  1100. event, context
  1101. )
  1102. if res is False:
  1103. logger.info(
  1104. "Event %s forbidden by third-party rules",
  1105. event,
  1106. )
  1107. raise SynapseError(
  1108. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  1109. )
  1110. elif new_content is not None:
  1111. # the third-party rules want to replace the event. We'll need to build a new
  1112. # event.
  1113. event, context = await self._rebuild_event_after_third_party_rules(
  1114. new_content, event
  1115. )
  1116. self.validator.validate_new(event, self.config)
  1117. await self._validate_event_relation(event)
  1118. logger.debug("Created event %s", event.event_id)
  1119. return event, context
  1120. async def _validate_event_relation(self, event: EventBase) -> None:
  1121. """
  1122. Ensure the relation data on a new event is not bogus.
  1123. Args:
  1124. event: The event being created.
  1125. Raises:
  1126. SynapseError if the event is invalid.
  1127. """
  1128. relation = relation_from_event(event)
  1129. if not relation:
  1130. return
  1131. parent_event = await self.store.get_event(relation.parent_id, allow_none=True)
  1132. if parent_event:
  1133. # And in the same room.
  1134. if parent_event.room_id != event.room_id:
  1135. raise SynapseError(400, "Relations must be in the same room")
  1136. else:
  1137. # There must be some reason that the client knows the event exists,
  1138. # see if there are existing relations. If so, assume everything is fine.
  1139. if not await self.store.event_is_target_of_relation(relation.parent_id):
  1140. # Otherwise, the client can't know about the parent event!
  1141. raise SynapseError(400, "Can't send relation to unknown event")
  1142. # If this event is an annotation then we check that that the sender
  1143. # can't annotate the same way twice (e.g. stops users from liking an
  1144. # event multiple times).
  1145. if relation.rel_type == RelationTypes.ANNOTATION:
  1146. aggregation_key = relation.aggregation_key
  1147. if aggregation_key is None:
  1148. raise SynapseError(400, "Missing aggregation key")
  1149. if len(aggregation_key) > 500:
  1150. raise SynapseError(400, "Aggregation key is too long")
  1151. already_exists = await self.store.has_user_annotated_event(
  1152. relation.parent_id, event.type, aggregation_key, event.sender
  1153. )
  1154. if already_exists:
  1155. raise SynapseError(
  1156. 400,
  1157. "Can't send same reaction twice",
  1158. errcode=Codes.DUPLICATE_ANNOTATION,
  1159. )
  1160. # Don't attempt to start a thread if the parent event is a relation.
  1161. elif relation.rel_type == RelationTypes.THREAD:
  1162. if await self.store.event_includes_relation(relation.parent_id):
  1163. raise SynapseError(
  1164. 400, "Cannot start threads from an event with a relation"
  1165. )
  1166. @measure_func("handle_new_client_event")
  1167. async def handle_new_client_event(
  1168. self,
  1169. requester: Requester,
  1170. events_and_context: List[Tuple[EventBase, EventContext]],
  1171. ratelimit: bool = True,
  1172. extra_users: Optional[List[UserID]] = None,
  1173. ignore_shadow_ban: bool = False,
  1174. ) -> EventBase:
  1175. """Processes new events. Please note that if batch persisting events, an error in
  1176. handling any one of these events will result in all of the events being dropped.
  1177. This includes deduplicating, checking auth, persisting,
  1178. notifying users, sending to remote servers, etc.
  1179. If called from a worker will hit out to the master process for final
  1180. processing.
  1181. Args:
  1182. requester
  1183. events_and_context: A list of one or more tuples of event, context to be persisted
  1184. ratelimit
  1185. extra_users: Any extra users to notify about event
  1186. ignore_shadow_ban: True if shadow-banned users should be allowed to
  1187. send this event.
  1188. Return:
  1189. If the event was deduplicated, the previous, duplicate, event. Otherwise,
  1190. `event`.
  1191. Raises:
  1192. ShadowBanError if the requester has been shadow-banned.
  1193. PartialStateConflictError if attempting to persist a partial state event in
  1194. a room that has been un-partial stated.
  1195. """
  1196. extra_users = extra_users or []
  1197. for event, context in events_and_context:
  1198. # we don't apply shadow-banning to membership events here. Invites are blocked
  1199. # higher up the stack, and we allow shadow-banned users to send join and leave
  1200. # events as normal.
  1201. if (
  1202. event.type != EventTypes.Member
  1203. and not ignore_shadow_ban
  1204. and requester.shadow_banned
  1205. ):
  1206. # We randomly sleep a bit just to annoy the requester.
  1207. await self.clock.sleep(random.randint(1, 10))
  1208. raise ShadowBanError()
  1209. if event.is_state():
  1210. prev_event = await self.deduplicate_state_event(event, context)
  1211. if prev_event is not None:
  1212. logger.info(
  1213. "Not bothering to persist state event %s duplicated by %s",
  1214. event.event_id,
  1215. prev_event.event_id,
  1216. )
  1217. return prev_event
  1218. if event.internal_metadata.is_out_of_band_membership():
  1219. # the only sort of out-of-band-membership events we expect to see here are
  1220. # invite rejections and rescinded knocks that we have generated ourselves.
  1221. assert event.type == EventTypes.Member
  1222. assert event.content["membership"] == Membership.LEAVE
  1223. else:
  1224. try:
  1225. validate_event_for_room_version(event)
  1226. # If we are persisting a batch of events the event(s) needed to auth the
  1227. # current event may be part of the batch and will not be in the DB yet
  1228. event_id_to_event = {e.event_id: e for e, _ in events_and_context}
  1229. batched_auth_events = {}
  1230. for event_id in event.auth_event_ids():
  1231. auth_event = event_id_to_event.get(event_id)
  1232. if auth_event:
  1233. batched_auth_events[event_id] = auth_event
  1234. await self._event_auth_handler.check_auth_rules_from_context(
  1235. event, batched_auth_events
  1236. )
  1237. except AuthError as err:
  1238. logger.warning("Denying new event %r because %s", event, err)
  1239. raise err
  1240. # Ensure that we can round trip before trying to persist in db
  1241. try:
  1242. dump = json_encoder.encode(event.content)
  1243. json_decoder.decode(dump)
  1244. except Exception:
  1245. logger.exception("Failed to encode content: %r", event.content)
  1246. raise
  1247. # We now persist the event (and update the cache in parallel, since we
  1248. # don't want to block on it).
  1249. event, context = events_and_context[0]
  1250. result, _ = await make_deferred_yieldable(
  1251. gather_results(
  1252. (
  1253. run_in_background(
  1254. self._persist_events,
  1255. requester=requester,
  1256. events_and_context=events_and_context,
  1257. ratelimit=ratelimit,
  1258. extra_users=extra_users,
  1259. ),
  1260. run_in_background(
  1261. self.cache_joined_hosts_for_events, events_and_context
  1262. ).addErrback(log_failure, "cache_joined_hosts_for_event failed"),
  1263. ),
  1264. consumeErrors=True,
  1265. )
  1266. ).addErrback(unwrapFirstError)
  1267. return result
  1268. async def _persist_events(
  1269. self,
  1270. requester: Requester,
  1271. events_and_context: List[Tuple[EventBase, EventContext]],
  1272. ratelimit: bool = True,
  1273. extra_users: Optional[List[UserID]] = None,
  1274. ) -> EventBase:
  1275. """Actually persists new events. Should only be called by
  1276. `handle_new_client_event`, and see its docstring for documentation of
  1277. the arguments. Please note that if batch persisting events, an error in
  1278. handling any one of these events will result in all of the events being dropped.
  1279. PartialStateConflictError: if attempting to persist a partial state event in
  1280. a room that has been un-partial stated.
  1281. """
  1282. await self._bulk_push_rule_evaluator.action_for_events_by_user(
  1283. events_and_context
  1284. )
  1285. try:
  1286. # If we're a worker we need to hit out to the master.
  1287. first_event, _ = events_and_context[0]
  1288. writer_instance = self._events_shard_config.get_instance(
  1289. first_event.room_id
  1290. )
  1291. if writer_instance != self._instance_name:
  1292. try:
  1293. result = await self.send_events(
  1294. instance_name=writer_instance,
  1295. events_and_context=events_and_context,
  1296. store=self.store,
  1297. requester=requester,
  1298. ratelimit=ratelimit,
  1299. extra_users=extra_users,
  1300. )
  1301. except SynapseError as e:
  1302. if e.code == HTTPStatus.CONFLICT:
  1303. raise PartialStateConflictError()
  1304. raise
  1305. stream_id = result["stream_id"]
  1306. event_id = result["event_id"]
  1307. # If we batch persisted events we return the last persisted event, otherwise
  1308. # we return the one event that was persisted
  1309. event, _ = events_and_context[-1]
  1310. if event_id != event.event_id:
  1311. # If we get a different event back then it means that its
  1312. # been de-duplicated, so we replace the given event with the
  1313. # one already persisted.
  1314. event = await self.store.get_event(event_id)
  1315. else:
  1316. # If we newly persisted the event then we need to update its
  1317. # stream_ordering entry manually (as it was persisted on
  1318. # another worker).
  1319. event.internal_metadata.stream_ordering = stream_id
  1320. return event
  1321. event = await self.persist_and_notify_client_events(
  1322. requester,
  1323. events_and_context,
  1324. ratelimit=ratelimit,
  1325. extra_users=extra_users,
  1326. )
  1327. return event
  1328. except Exception:
  1329. for event, _ in events_and_context:
  1330. # Ensure that we actually remove the entries in the push actions
  1331. # staging area, if we calculated them.
  1332. await self.store.remove_push_actions_from_staging(event.event_id)
  1333. raise
  1334. async def cache_joined_hosts_for_events(
  1335. self, events_and_context: List[Tuple[EventBase, EventContext]]
  1336. ) -> None:
  1337. """Precalculate the joined hosts at each of the given events, when using Redis, so that
  1338. external federation senders don't have to recalculate it themselves.
  1339. """
  1340. if not self._external_cache.is_enabled():
  1341. return
  1342. # If external cache is enabled we should always have this.
  1343. assert self._external_cache_joined_hosts_updates is not None
  1344. for event, event_context in events_and_context:
  1345. if event_context.partial_state:
  1346. # To populate the cache for a partial-state event, we either have to
  1347. # block until full state, which the code below does, or change the
  1348. # meaning of cache values to be the list of hosts to which we plan to
  1349. # send events and calculate that instead.
  1350. #
  1351. # The federation senders don't use the external cache when sending
  1352. # events in partial-state rooms anyway, so let's not bother populating
  1353. # the cache.
  1354. continue
  1355. # We actually store two mappings, event ID -> prev state group,
  1356. # state group -> joined hosts, which is much more space efficient
  1357. # than event ID -> joined hosts.
  1358. #
  1359. # Note: We have to cache event ID -> prev state group, as we don't
  1360. # store that in the DB.
  1361. #
  1362. # Note: We set the state group -> joined hosts cache if it hasn't been
  1363. # set for a while, so that the expiry time is reset.
  1364. state_entry = await self.state.resolve_state_groups_for_events(
  1365. event.room_id, event_ids=event.prev_event_ids()
  1366. )
  1367. if state_entry.state_group:
  1368. await self._external_cache.set(
  1369. "event_to_prev_state_group",
  1370. event.event_id,
  1371. state_entry.state_group,
  1372. expiry_ms=60 * 60 * 1000,
  1373. )
  1374. if state_entry.state_group in self._external_cache_joined_hosts_updates:
  1375. return
  1376. state = await state_entry.get_state(
  1377. self._storage_controllers.state, StateFilter.all()
  1378. )
  1379. with opentracing.start_active_span("get_joined_hosts"):
  1380. joined_hosts = await self.store.get_joined_hosts(
  1381. event.room_id, state, state_entry
  1382. )
  1383. # Note that the expiry times must be larger than the expiry time in
  1384. # _external_cache_joined_hosts_updates.
  1385. await self._external_cache.set(
  1386. "get_joined_hosts",
  1387. str(state_entry.state_group),
  1388. list(joined_hosts),
  1389. expiry_ms=60 * 60 * 1000,
  1390. )
  1391. self._external_cache_joined_hosts_updates[
  1392. state_entry.state_group
  1393. ] = None
  1394. async def _validate_canonical_alias(
  1395. self,
  1396. directory_handler: DirectoryHandler,
  1397. room_alias_str: str,
  1398. expected_room_id: str,
  1399. ) -> None:
  1400. """
  1401. Ensure that the given room alias points to the expected room ID.
  1402. Args:
  1403. directory_handler: The directory handler object.
  1404. room_alias_str: The room alias to check.
  1405. expected_room_id: The room ID that the alias should point to.
  1406. """
  1407. room_alias = RoomAlias.from_string(room_alias_str)
  1408. try:
  1409. mapping = await directory_handler.get_association(room_alias)
  1410. except SynapseError as e:
  1411. # Turn M_NOT_FOUND errors into M_BAD_ALIAS errors.
  1412. if e.errcode == Codes.NOT_FOUND:
  1413. raise SynapseError(
  1414. 400,
  1415. "Room alias %s does not point to the room" % (room_alias_str,),
  1416. Codes.BAD_ALIAS,
  1417. )
  1418. raise
  1419. if mapping["room_id"] != expected_room_id:
  1420. raise SynapseError(
  1421. 400,
  1422. "Room alias %s does not point to the room" % (room_alias_str,),
  1423. Codes.BAD_ALIAS,
  1424. )
  1425. async def persist_and_notify_client_events(
  1426. self,
  1427. requester: Requester,
  1428. events_and_context: List[Tuple[EventBase, EventContext]],
  1429. ratelimit: bool = True,
  1430. extra_users: Optional[List[UserID]] = None,
  1431. ) -> EventBase:
  1432. """Called when we have fully built the events, have already
  1433. calculated the push actions for the events, and checked auth.
  1434. This should only be run on the instance in charge of persisting events.
  1435. Please note that if batch persisting events, an error in
  1436. handling any one of these events will result in all of the events being dropped.
  1437. Returns:
  1438. The persisted event, if one event is passed in, or the last event in the
  1439. list in the case of batch persisting. If only one event was persisted, the
  1440. returned event may be different than the given event if it was de-duplicated
  1441. (e.g. because we had already persisted an event with the same transaction ID.)
  1442. Raises:
  1443. PartialStateConflictError: if attempting to persist a partial state event in
  1444. a room that has been un-partial stated.
  1445. """
  1446. extra_users = extra_users or []
  1447. for event, context in events_and_context:
  1448. assert self._events_shard_config.should_handle(
  1449. self._instance_name, event.room_id
  1450. )
  1451. if ratelimit:
  1452. # We check if this is a room admin redacting an event so that we
  1453. # can apply different ratelimiting. We do this by simply checking
  1454. # it's not a self-redaction (to avoid having to look up whether the
  1455. # user is actually admin or not).
  1456. is_admin_redaction = False
  1457. if event.type == EventTypes.Redaction:
  1458. assert event.redacts is not None
  1459. original_event = await self.store.get_event(
  1460. event.redacts,
  1461. redact_behaviour=EventRedactBehaviour.as_is,
  1462. get_prev_content=False,
  1463. allow_rejected=False,
  1464. allow_none=True,
  1465. )
  1466. is_admin_redaction = bool(
  1467. original_event and event.sender != original_event.sender
  1468. )
  1469. await self.request_ratelimiter.ratelimit(
  1470. requester, is_admin_redaction=is_admin_redaction
  1471. )
  1472. # run checks/actions on event based on type
  1473. if event.type == EventTypes.Member and event.membership == Membership.JOIN:
  1474. (
  1475. current_membership,
  1476. _,
  1477. ) = await self.store.get_local_current_membership_for_user_in_room(
  1478. event.state_key, event.room_id
  1479. )
  1480. if current_membership != Membership.JOIN:
  1481. self._notifier.notify_user_joined_room(
  1482. event.event_id, event.room_id
  1483. )
  1484. await self._maybe_kick_guest_users(event, context)
  1485. if event.type == EventTypes.CanonicalAlias:
  1486. # Validate a newly added alias or newly added alt_aliases.
  1487. original_alias = None
  1488. original_alt_aliases: object = []
  1489. original_event_id = event.unsigned.get("replaces_state")
  1490. if original_event_id:
  1491. original_alias_event = await self.store.get_event(original_event_id)
  1492. if original_alias_event:
  1493. original_alias = original_alias_event.content.get("alias", None)
  1494. original_alt_aliases = original_alias_event.content.get(
  1495. "alt_aliases", []
  1496. )
  1497. # Check the alias is currently valid (if it has changed).
  1498. room_alias_str = event.content.get("alias", None)
  1499. directory_handler = self.hs.get_directory_handler()
  1500. if room_alias_str and room_alias_str != original_alias:
  1501. await self._validate_canonical_alias(
  1502. directory_handler, room_alias_str, event.room_id
  1503. )
  1504. # Check that alt_aliases is the proper form.
  1505. alt_aliases = event.content.get("alt_aliases", [])
  1506. if not isinstance(alt_aliases, (list, tuple)):
  1507. raise SynapseError(
  1508. 400,
  1509. "The alt_aliases property must be a list.",
  1510. Codes.INVALID_PARAM,
  1511. )
  1512. # If the old version of alt_aliases is of an unknown form,
  1513. # completely replace it.
  1514. if not isinstance(original_alt_aliases, (list, tuple)):
  1515. # TODO: check that the original_alt_aliases' entries are all strings
  1516. original_alt_aliases = []
  1517. # Check that each alias is currently valid.
  1518. new_alt_aliases = set(alt_aliases) - set(original_alt_aliases)
  1519. if new_alt_aliases:
  1520. for alias_str in new_alt_aliases:
  1521. await self._validate_canonical_alias(
  1522. directory_handler, alias_str, event.room_id
  1523. )
  1524. federation_handler = self.hs.get_federation_handler()
  1525. if event.type == EventTypes.Member:
  1526. if event.content["membership"] == Membership.INVITE:
  1527. maybe_upsert_event_field(
  1528. event,
  1529. event.unsigned,
  1530. "invite_room_state",
  1531. await self.store.get_stripped_room_state_from_event_context(
  1532. context,
  1533. self.room_prejoin_state_types,
  1534. membership_user_id=event.sender,
  1535. ),
  1536. )
  1537. invitee = UserID.from_string(event.state_key)
  1538. if not self.hs.is_mine(invitee):
  1539. # TODO: Can we add signature from remote server in a nicer
  1540. # way? If we have been invited by a remote server, we need
  1541. # to get them to sign the event.
  1542. returned_invite = await federation_handler.send_invite(
  1543. invitee.domain, event
  1544. )
  1545. event.unsigned.pop("room_state", None)
  1546. # TODO: Make sure the signatures actually are correct.
  1547. event.signatures.update(returned_invite.signatures)
  1548. if event.content["membership"] == Membership.KNOCK:
  1549. maybe_upsert_event_field(
  1550. event,
  1551. event.unsigned,
  1552. "knock_room_state",
  1553. await self.store.get_stripped_room_state_from_event_context(
  1554. context,
  1555. self.room_prejoin_state_types,
  1556. ),
  1557. )
  1558. if event.type == EventTypes.Redaction:
  1559. assert event.redacts is not None
  1560. original_event = await self.store.get_event(
  1561. event.redacts,
  1562. redact_behaviour=EventRedactBehaviour.as_is,
  1563. get_prev_content=False,
  1564. allow_rejected=False,
  1565. allow_none=True,
  1566. )
  1567. room_version = await self.store.get_room_version_id(event.room_id)
  1568. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1569. # we can make some additional checks now if we have the original event.
  1570. if original_event:
  1571. if original_event.type == EventTypes.Create:
  1572. raise AuthError(403, "Redacting create events is not permitted")
  1573. if original_event.room_id != event.room_id:
  1574. raise SynapseError(
  1575. 400, "Cannot redact event from a different room"
  1576. )
  1577. if original_event.type == EventTypes.ServerACL:
  1578. raise AuthError(
  1579. 403, "Redacting server ACL events is not permitted"
  1580. )
  1581. # Add a little safety stop-gap to prevent people from trying to
  1582. # redact MSC2716 related events when they're in a room version
  1583. # which does not support it yet. We allow people to use MSC2716
  1584. # events in existing room versions but only from the room
  1585. # creator since it does not require any changes to the auth
  1586. # rules and in effect, the redaction algorithm . In the
  1587. # supported room version, we add the `historical` power level to
  1588. # auth the MSC2716 related events and adjust the redaction
  1589. # algorthim to keep the `historical` field around (redacting an
  1590. # event should only strip fields which don't affect the
  1591. # structural protocol level).
  1592. is_msc2716_event = (
  1593. original_event.type == EventTypes.MSC2716_INSERTION
  1594. or original_event.type == EventTypes.MSC2716_BATCH
  1595. or original_event.type == EventTypes.MSC2716_MARKER
  1596. )
  1597. if not room_version_obj.msc2716_historical and is_msc2716_event:
  1598. raise AuthError(
  1599. 403,
  1600. "Redacting MSC2716 events is not supported in this room version",
  1601. )
  1602. event_types = event_auth.auth_types_for_event(event.room_version, event)
  1603. prev_state_ids = await context.get_prev_state_ids(
  1604. StateFilter.from_types(event_types)
  1605. )
  1606. auth_events_ids = self._event_auth_handler.compute_auth_events(
  1607. event, prev_state_ids, for_verification=True
  1608. )
  1609. auth_events_map = await self.store.get_events(auth_events_ids)
  1610. auth_events = {
  1611. (e.type, e.state_key): e for e in auth_events_map.values()
  1612. }
  1613. if event_auth.check_redaction(
  1614. room_version_obj, event, auth_events=auth_events
  1615. ):
  1616. # this user doesn't have 'redact' rights, so we need to do some more
  1617. # checks on the original event. Let's start by checking the original
  1618. # event exists.
  1619. if not original_event:
  1620. raise NotFoundError(
  1621. "Could not find event %s" % (event.redacts,)
  1622. )
  1623. if event.user_id != original_event.user_id:
  1624. raise AuthError(
  1625. 403, "You don't have permission to redact events"
  1626. )
  1627. # all the checks are done.
  1628. event.internal_metadata.recheck_redaction = False
  1629. if event.type == EventTypes.Create:
  1630. prev_state_ids = await context.get_prev_state_ids()
  1631. if prev_state_ids:
  1632. raise AuthError(403, "Changing the room create event is forbidden")
  1633. if event.type == EventTypes.MSC2716_INSERTION:
  1634. room_version = await self.store.get_room_version_id(event.room_id)
  1635. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1636. create_event = await self.store.get_create_event_for_room(event.room_id)
  1637. room_creator = create_event.content.get(EventContentFields.ROOM_CREATOR)
  1638. # Only check an insertion event if the room version
  1639. # supports it or the event is from the room creator.
  1640. if room_version_obj.msc2716_historical or (
  1641. self.config.experimental.msc2716_enabled
  1642. and event.sender == room_creator
  1643. ):
  1644. next_batch_id = event.content.get(
  1645. EventContentFields.MSC2716_NEXT_BATCH_ID
  1646. )
  1647. conflicting_insertion_event_id = None
  1648. if next_batch_id:
  1649. conflicting_insertion_event_id = (
  1650. await self.store.get_insertion_event_id_by_batch_id(
  1651. event.room_id, next_batch_id
  1652. )
  1653. )
  1654. if conflicting_insertion_event_id is not None:
  1655. # The current insertion event that we're processing is invalid
  1656. # because an insertion event already exists in the room with the
  1657. # same next_batch_id. We can't allow multiple because the batch
  1658. # pointing will get weird, e.g. we can't determine which insertion
  1659. # event the batch event is pointing to.
  1660. raise SynapseError(
  1661. HTTPStatus.BAD_REQUEST,
  1662. "Another insertion event already exists with the same next_batch_id",
  1663. errcode=Codes.INVALID_PARAM,
  1664. )
  1665. # Mark any `m.historical` messages as backfilled so they don't appear
  1666. # in `/sync` and have the proper decrementing `stream_ordering` as we import
  1667. backfilled = False
  1668. if event.internal_metadata.is_historical():
  1669. backfilled = True
  1670. assert self._storage_controllers.persistence is not None
  1671. (
  1672. persisted_events,
  1673. max_stream_token,
  1674. ) = await self._storage_controllers.persistence.persist_events(
  1675. events_and_context, backfilled=backfilled
  1676. )
  1677. events_and_pos = []
  1678. for event in persisted_events:
  1679. if self._ephemeral_events_enabled:
  1680. # If there's an expiry timestamp on the event, schedule its expiry.
  1681. self._message_handler.maybe_schedule_expiry(event)
  1682. stream_ordering = event.internal_metadata.stream_ordering
  1683. assert stream_ordering is not None
  1684. pos = PersistedEventPosition(self._instance_name, stream_ordering)
  1685. events_and_pos.append((event, pos))
  1686. if event.type == EventTypes.Message:
  1687. # We don't want to block sending messages on any presence code. This
  1688. # matters as sometimes presence code can take a while.
  1689. run_as_background_process(
  1690. "bump_presence_active_time", self._bump_active_time, requester.user
  1691. )
  1692. async def _notify() -> None:
  1693. try:
  1694. await self.notifier.on_new_room_events(
  1695. events_and_pos, max_stream_token, extra_users=extra_users
  1696. )
  1697. except Exception:
  1698. logger.exception("Error notifying about new room events")
  1699. run_in_background(_notify)
  1700. return persisted_events[-1]
  1701. async def _maybe_kick_guest_users(
  1702. self, event: EventBase, context: EventContext
  1703. ) -> None:
  1704. if event.type != EventTypes.GuestAccess:
  1705. return
  1706. guest_access = event.content.get(EventContentFields.GUEST_ACCESS)
  1707. if guest_access == GuestAccess.CAN_JOIN:
  1708. return
  1709. current_state_ids = await context.get_current_state_ids()
  1710. # since this is a client-generated event, it cannot be an outlier and we must
  1711. # therefore have the state ids.
  1712. assert current_state_ids is not None
  1713. current_state_dict = await self.store.get_events(
  1714. list(current_state_ids.values())
  1715. )
  1716. current_state = list(current_state_dict.values())
  1717. logger.info("maybe_kick_guest_users %r", current_state)
  1718. await self.hs.get_room_member_handler().kick_guest_users(current_state)
  1719. async def _bump_active_time(self, user: UserID) -> None:
  1720. try:
  1721. presence = self.hs.get_presence_handler()
  1722. await presence.bump_presence_active_time(user)
  1723. except Exception:
  1724. logger.exception("Error bumping presence active time")
  1725. async def _send_dummy_events_to_fill_extremities(self) -> None:
  1726. """Background task to send dummy events into rooms that have a large
  1727. number of extremities
  1728. """
  1729. self._expire_rooms_to_exclude_from_dummy_event_insertion()
  1730. room_ids = await self.store.get_rooms_with_many_extremities(
  1731. min_count=self._dummy_events_threshold,
  1732. limit=5,
  1733. room_id_filter=self._rooms_to_exclude_from_dummy_event_insertion.keys(),
  1734. )
  1735. for room_id in room_ids:
  1736. dummy_event_sent = await self._send_dummy_event_for_room(room_id)
  1737. if not dummy_event_sent:
  1738. # Did not find a valid user in the room, so remove from future attempts
  1739. # Exclusion is time limited, so the room will be rechecked in the future
  1740. # dependent on _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY
  1741. logger.info(
  1742. "Failed to send dummy event into room %s. Will exclude it from "
  1743. "future attempts until cache expires" % (room_id,)
  1744. )
  1745. now = self.clock.time_msec()
  1746. self._rooms_to_exclude_from_dummy_event_insertion[room_id] = now
  1747. async def _send_dummy_event_for_room(self, room_id: str) -> bool:
  1748. """Attempt to send a dummy event for the given room.
  1749. Args:
  1750. room_id: room to try to send an event from
  1751. Returns:
  1752. True if a dummy event was successfully sent. False if no user was able
  1753. to send an event.
  1754. """
  1755. # For each room we need to find a joined member we can use to send
  1756. # the dummy event with.
  1757. members = await self.store.get_local_users_in_room(room_id)
  1758. for user_id in members:
  1759. requester = create_requester(user_id, authenticated_entity=self.server_name)
  1760. try:
  1761. # Try several times, it could fail with PartialStateConflictError
  1762. # in handle_new_client_event, cf comment in except block.
  1763. max_retries = 5
  1764. for i in range(max_retries):
  1765. try:
  1766. event, unpersisted_context = await self.create_event(
  1767. requester,
  1768. {
  1769. "type": EventTypes.Dummy,
  1770. "content": {},
  1771. "room_id": room_id,
  1772. "sender": user_id,
  1773. },
  1774. )
  1775. context = await unpersisted_context.persist(event)
  1776. event.internal_metadata.proactively_send = False
  1777. # Since this is a dummy-event it is OK if it is sent by a
  1778. # shadow-banned user.
  1779. await self.handle_new_client_event(
  1780. requester,
  1781. events_and_context=[(event, context)],
  1782. ratelimit=False,
  1783. ignore_shadow_ban=True,
  1784. )
  1785. break
  1786. except PartialStateConflictError as e:
  1787. # Persisting couldn't happen because the room got un-partial stated
  1788. # in the meantime and context needs to be recomputed, so let's do so.
  1789. if i == max_retries - 1:
  1790. raise e
  1791. pass
  1792. return True
  1793. except AuthError:
  1794. logger.info(
  1795. "Failed to send dummy event into room %s for user %s due to "
  1796. "lack of power. Will try another user" % (room_id, user_id)
  1797. )
  1798. return False
  1799. def _expire_rooms_to_exclude_from_dummy_event_insertion(self) -> None:
  1800. expire_before = self.clock.time_msec() - _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY
  1801. to_expire = set()
  1802. for room_id, time in self._rooms_to_exclude_from_dummy_event_insertion.items():
  1803. if time < expire_before:
  1804. to_expire.add(room_id)
  1805. for room_id in to_expire:
  1806. logger.debug(
  1807. "Expiring room id %s from dummy event insertion exclusion cache",
  1808. room_id,
  1809. )
  1810. del self._rooms_to_exclude_from_dummy_event_insertion[room_id]
  1811. async def _rebuild_event_after_third_party_rules(
  1812. self, third_party_result: dict, original_event: EventBase
  1813. ) -> Tuple[EventBase, UnpersistedEventContextBase]:
  1814. # the third_party_event_rules want to replace the event.
  1815. # we do some basic checks, and then return the replacement event.
  1816. # Construct a new EventBuilder and validate it, which helps with the
  1817. # rest of these checks.
  1818. try:
  1819. builder = self.event_builder_factory.for_room_version(
  1820. original_event.room_version, third_party_result
  1821. )
  1822. self.validator.validate_builder(builder)
  1823. except SynapseError as e:
  1824. raise Exception(
  1825. "Third party rules module created an invalid event: " + e.msg,
  1826. )
  1827. immutable_fields = [
  1828. # changing the room is going to break things: we've already checked that the
  1829. # room exists, and are holding a concurrency limiter token for that room.
  1830. # Also, we might need to use a different room version.
  1831. "room_id",
  1832. # changing the type or state key might work, but we'd need to check that the
  1833. # calling functions aren't making assumptions about them.
  1834. "type",
  1835. "state_key",
  1836. ]
  1837. for k in immutable_fields:
  1838. if getattr(builder, k, None) != original_event.get(k):
  1839. raise Exception(
  1840. "Third party rules module created an invalid event: "
  1841. "cannot change field " + k
  1842. )
  1843. # check that the new sender belongs to this HS
  1844. if not self.hs.is_mine_id(builder.sender):
  1845. raise Exception(
  1846. "Third party rules module created an invalid event: "
  1847. "invalid sender " + builder.sender
  1848. )
  1849. # copy over the original internal metadata
  1850. for k, v in original_event.internal_metadata.get_dict().items():
  1851. setattr(builder.internal_metadata, k, v)
  1852. # modules can send new state events, so we re-calculate the auth events just in
  1853. # case.
  1854. prev_event_ids = await self.store.get_prev_events_for_room(builder.room_id)
  1855. event = await builder.build(
  1856. prev_event_ids=prev_event_ids,
  1857. auth_event_ids=None,
  1858. )
  1859. # we rebuild the event context, to be on the safe side. If nothing else,
  1860. # delta_ids might need an update.
  1861. context = await self.state.calculate_context_info(event)
  1862. return event, context