message.py 82 KB

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