message.py 76 KB

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