message.py 76 KB

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