Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

1851 rinda
76 KiB

  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. StateFilter.from_types([(EventTypes.Member, None)])
  545. )
  546. prev_event_id = prev_state_ids.get((EventTypes.Member, event.sender))
  547. prev_event = (
  548. await self.store.get_event(prev_event_id, allow_none=True)
  549. if prev_event_id
  550. else None
  551. )
  552. if not prev_event or prev_event.membership != Membership.JOIN:
  553. logger.warning(
  554. (
  555. "Attempt to send `m.room.aliases` in room %s by user %s but"
  556. " membership is %s"
  557. ),
  558. event.room_id,
  559. event.sender,
  560. prev_event.membership if prev_event else None,
  561. )
  562. raise AuthError(
  563. 403, "You must be in the room to create an alias for it"
  564. )
  565. self.validator.validate_new(event, self.config)
  566. return event, context
  567. async def _is_exempt_from_privacy_policy(
  568. self, builder: EventBuilder, requester: Requester
  569. ) -> bool:
  570. """ "Determine if an event to be sent is exempt from having to consent
  571. to the privacy policy
  572. Args:
  573. builder: event being created
  574. requester: user requesting this event
  575. Returns:
  576. true if the event can be sent without the user consenting
  577. """
  578. # the only thing the user can do is join the server notices room.
  579. if builder.type == EventTypes.Member:
  580. membership = builder.content.get("membership", None)
  581. if membership == Membership.JOIN:
  582. return await self._is_server_notices_room(builder.room_id)
  583. elif membership == Membership.LEAVE:
  584. # the user is always allowed to leave (but not kick people)
  585. return builder.state_key == requester.user.to_string()
  586. return False
  587. async def _is_server_notices_room(self, room_id: str) -> bool:
  588. if self.config.servernotices.server_notices_mxid is None:
  589. return False
  590. user_ids = await self.store.get_users_in_room(room_id)
  591. return self.config.servernotices.server_notices_mxid in user_ids
  592. async def assert_accepted_privacy_policy(self, requester: Requester) -> None:
  593. """Check if a user has accepted the privacy policy
  594. Called when the given user is about to do something that requires
  595. privacy consent. We see if the user is exempt and otherwise check that
  596. they have given consent. If they have not, a ConsentNotGiven error is
  597. raised.
  598. Args:
  599. requester: The user making the request
  600. Returns:
  601. Returns normally if the user has consented or is exempt
  602. Raises:
  603. ConsentNotGivenError: if the user has not given consent yet
  604. """
  605. if self._block_events_without_consent_error is None:
  606. return
  607. # exempt AS users from needing consent
  608. if requester.app_service is not None:
  609. return
  610. user_id = requester.authenticated_entity
  611. if not user_id.startswith("@"):
  612. # The authenticated entity might not be a user, e.g. if it's the
  613. # server puppetting the user.
  614. return
  615. user = UserID.from_string(user_id)
  616. # exempt the system notices user
  617. if (
  618. self.config.servernotices.server_notices_mxid is not None
  619. and user_id == self.config.servernotices.server_notices_mxid
  620. ):
  621. return
  622. u = await self.store.get_user_by_id(user_id)
  623. assert u is not None
  624. if u["user_type"] in (UserTypes.SUPPORT, UserTypes.BOT):
  625. # support and bot users are not required to consent
  626. return
  627. if u["appservice_id"] is not None:
  628. # users registered by an appservice are exempt
  629. return
  630. if u["consent_version"] == self.config.consent.user_consent_version:
  631. return
  632. consent_uri = self._consent_uri_builder.build_user_consent_uri(user.localpart)
  633. msg = self._block_events_without_consent_error % {"consent_uri": consent_uri}
  634. raise ConsentNotGivenError(msg=msg, consent_uri=consent_uri)
  635. async def deduplicate_state_event(
  636. self, event: EventBase, context: EventContext
  637. ) -> Optional[EventBase]:
  638. """
  639. Checks whether event is in the latest resolved state in context.
  640. Args:
  641. event: The event to check for duplication.
  642. context: The event context.
  643. Returns:
  644. The previous version of the event is returned, if it is found in the
  645. event context. Otherwise, None is returned.
  646. """
  647. if event.internal_metadata.is_outlier():
  648. # This can happen due to out of band memberships
  649. return None
  650. prev_state_ids = await context.get_prev_state_ids(
  651. StateFilter.from_types([(event.type, None)])
  652. )
  653. prev_event_id = prev_state_ids.get((event.type, event.state_key))
  654. if not prev_event_id:
  655. return None
  656. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  657. if not prev_event:
  658. return None
  659. if prev_event and event.user_id == prev_event.user_id:
  660. prev_content = encode_canonical_json(prev_event.content)
  661. next_content = encode_canonical_json(event.content)
  662. if prev_content == next_content:
  663. return prev_event
  664. return None
  665. async def create_and_send_nonmember_event(
  666. self,
  667. requester: Requester,
  668. event_dict: dict,
  669. allow_no_prev_events: bool = False,
  670. prev_event_ids: Optional[List[str]] = None,
  671. state_event_ids: Optional[List[str]] = None,
  672. ratelimit: bool = True,
  673. txn_id: Optional[str] = None,
  674. ignore_shadow_ban: bool = False,
  675. outlier: bool = False,
  676. historical: bool = False,
  677. depth: Optional[int] = None,
  678. ) -> Tuple[EventBase, int]:
  679. """
  680. Creates an event, then sends it.
  681. See self.create_event and self.handle_new_client_event.
  682. Args:
  683. requester: The requester sending the event.
  684. event_dict: An entire event.
  685. allow_no_prev_events: Whether to allow this event to be created an empty
  686. list of prev_events. Normally this is prohibited just because most
  687. events should have a prev_event and we should only use this in special
  688. cases like MSC2716.
  689. prev_event_ids:
  690. The event IDs to use as the prev events.
  691. Should normally be left as None to automatically request them
  692. from the database.
  693. state_event_ids:
  694. The full state at a given event. This is used particularly by the MSC2716
  695. /batch_send endpoint. One use case is with insertion events which float at
  696. the beginning of a historical batch and don't have any `prev_events` to
  697. derive from; we add all of these state events as the explicit state so the
  698. rest of the historical batch can inherit the same state and state_group.
  699. This should normally be left as None, which will cause the auth_event_ids
  700. to be calculated based on the room state at the prev_events.
  701. ratelimit: Whether to rate limit this send.
  702. txn_id: The transaction ID.
  703. ignore_shadow_ban: True if shadow-banned users should be allowed to
  704. send this event.
  705. outlier: Indicates whether the event is an `outlier`, i.e. if
  706. it's from an arbitrary point and floating in the DAG as
  707. opposed to being inline with the current DAG.
  708. historical: Indicates whether the message is being inserted
  709. back in time around some existing events. This is used to skip
  710. a few checks and mark the event as backfilled.
  711. depth: Override the depth used to order the event in the DAG.
  712. Should normally be set to None, which will cause the depth to be calculated
  713. based on the prev_events.
  714. Returns:
  715. The event, and its stream ordering (if deduplication happened,
  716. the previous, duplicate event).
  717. Raises:
  718. ShadowBanError if the requester has been shadow-banned.
  719. """
  720. if event_dict["type"] == EventTypes.Member:
  721. raise SynapseError(
  722. 500, "Tried to send member event through non-member codepath"
  723. )
  724. if not ignore_shadow_ban and requester.shadow_banned:
  725. # We randomly sleep a bit just to annoy the requester.
  726. await self.clock.sleep(random.randint(1, 10))
  727. raise ShadowBanError()
  728. # We limit the number of concurrent event sends in a room so that we
  729. # don't fork the DAG too much. If we don't limit then we can end up in
  730. # a situation where event persistence can't keep up, causing
  731. # extremities to pile up, which in turn leads to state resolution
  732. # taking longer.
  733. async with self.limiter.queue(event_dict["room_id"]):
  734. if txn_id and requester.access_token_id:
  735. existing_event_id = await self.store.get_event_id_from_transaction_id(
  736. event_dict["room_id"],
  737. requester.user.to_string(),
  738. requester.access_token_id,
  739. txn_id,
  740. )
  741. if existing_event_id:
  742. event = await self.store.get_event(existing_event_id)
  743. # we know it was persisted, so must have a stream ordering
  744. assert event.internal_metadata.stream_ordering
  745. return event, event.internal_metadata.stream_ordering
  746. event, context = await self.create_event(
  747. requester,
  748. event_dict,
  749. txn_id=txn_id,
  750. allow_no_prev_events=allow_no_prev_events,
  751. prev_event_ids=prev_event_ids,
  752. state_event_ids=state_event_ids,
  753. outlier=outlier,
  754. historical=historical,
  755. depth=depth,
  756. )
  757. assert self.hs.is_mine_id(event.sender), "User must be our own: %s" % (
  758. event.sender,
  759. )
  760. spam_check_result = await self.spam_checker.check_event_for_spam(event)
  761. if spam_check_result != self.spam_checker.NOT_SPAM:
  762. if isinstance(spam_check_result, Codes):
  763. raise SynapseError(
  764. 403,
  765. "This message has been rejected as probable spam",
  766. spam_check_result,
  767. )
  768. # Backwards compatibility: if the return value is not an error code, it
  769. # means the module returned an error message to be included in the
  770. # SynapseError (which is now deprecated).
  771. raise SynapseError(
  772. 403,
  773. spam_check_result,
  774. Codes.FORBIDDEN,
  775. )
  776. ev = await self.handle_new_client_event(
  777. requester=requester,
  778. event=event,
  779. context=context,
  780. ratelimit=ratelimit,
  781. ignore_shadow_ban=ignore_shadow_ban,
  782. )
  783. # we know it was persisted, so must have a stream ordering
  784. assert ev.internal_metadata.stream_ordering
  785. return ev, ev.internal_metadata.stream_ordering
  786. @measure_func("create_new_client_event")
  787. async def create_new_client_event(
  788. self,
  789. builder: EventBuilder,
  790. requester: Optional[Requester] = None,
  791. allow_no_prev_events: bool = False,
  792. prev_event_ids: Optional[List[str]] = None,
  793. auth_event_ids: Optional[List[str]] = None,
  794. state_event_ids: Optional[List[str]] = None,
  795. depth: Optional[int] = None,
  796. ) -> Tuple[EventBase, EventContext]:
  797. """Create a new event for a local client
  798. Args:
  799. builder:
  800. requester:
  801. allow_no_prev_events: Whether to allow this event to be created an empty
  802. list of prev_events. Normally this is prohibited just because most
  803. events should have a prev_event and we should only use this in special
  804. cases like MSC2716.
  805. prev_event_ids:
  806. the forward extremities to use as the prev_events for the
  807. new event.
  808. If None, they will be requested from the database.
  809. auth_event_ids:
  810. The event ids to use as the auth_events for the new event.
  811. Should normally be left as None, which will cause them to be calculated
  812. based on the room state at the prev_events.
  813. state_event_ids:
  814. The full state at a given event. This is used particularly by the MSC2716
  815. /batch_send endpoint. One use case is with insertion events which float at
  816. the beginning of a historical batch and don't have any `prev_events` to
  817. derive from; we add all of these state events as the explicit state so the
  818. rest of the historical batch can inherit the same state and state_group.
  819. This should normally be left as None, which will cause the auth_event_ids
  820. to be calculated based on the room state at the prev_events.
  821. depth: Override the depth used to order the event in the DAG.
  822. Should normally be set to None, which will cause the depth to be calculated
  823. based on the prev_events.
  824. Returns:
  825. Tuple of created event, context
  826. """
  827. # Strip down the state_event_ids to only what we need to auth the event.
  828. # For example, we don't need extra m.room.member that don't match event.sender
  829. if state_event_ids is not None:
  830. # Do a quick check to make sure that prev_event_ids is present to
  831. # make the type-checking around `builder.build` happy.
  832. # prev_event_ids could be an empty array though.
  833. assert prev_event_ids is not None
  834. temp_event = await builder.build(
  835. prev_event_ids=prev_event_ids,
  836. auth_event_ids=state_event_ids,
  837. depth=depth,
  838. )
  839. state_events = await self.store.get_events_as_list(state_event_ids)
  840. # Create a StateMap[str]
  841. state_map = {(e.type, e.state_key): e.event_id for e in state_events}
  842. # Actually strip down and only use the necessary auth events
  843. auth_event_ids = self._event_auth_handler.compute_auth_events(
  844. event=temp_event,
  845. current_state_ids=state_map,
  846. for_verification=False,
  847. )
  848. if prev_event_ids is not None:
  849. assert (
  850. len(prev_event_ids) <= 10
  851. ), "Attempting to create an event with %i prev_events" % (
  852. len(prev_event_ids),
  853. )
  854. else:
  855. prev_event_ids = await self.store.get_prev_events_for_room(builder.room_id)
  856. # Do a quick sanity check here, rather than waiting until we've created the
  857. # event and then try to auth it (which fails with a somewhat confusing "No
  858. # create event in auth events")
  859. if allow_no_prev_events:
  860. # We allow events with no `prev_events` but it better have some `auth_events`
  861. assert (
  862. builder.type == EventTypes.Create
  863. # Allow an event to have empty list of prev_event_ids
  864. # only if it has auth_event_ids.
  865. or auth_event_ids
  866. ), "Attempting to create a non-m.room.create event with no prev_events or auth_event_ids"
  867. else:
  868. # we now ought to have some prev_events (unless it's a create event).
  869. assert (
  870. builder.type == EventTypes.Create or prev_event_ids
  871. ), "Attempting to create a non-m.room.create event with no prev_events"
  872. event = await builder.build(
  873. prev_event_ids=prev_event_ids,
  874. auth_event_ids=auth_event_ids,
  875. depth=depth,
  876. )
  877. # Pass on the outlier property from the builder to the event
  878. # after it is created
  879. if builder.internal_metadata.outlier:
  880. event.internal_metadata.outlier = True
  881. context = EventContext.for_outlier(self.storage)
  882. elif (
  883. event.type == EventTypes.MSC2716_INSERTION
  884. and state_event_ids
  885. and builder.internal_metadata.is_historical()
  886. ):
  887. # Add explicit state to the insertion event so it has state to derive
  888. # from even though it's floating with no `prev_events`. The rest of
  889. # the batch can derive from this state and state_group.
  890. #
  891. # TODO(faster_joins): figure out how this works, and make sure that the
  892. # old state is complete.
  893. old_state = await self.store.get_events_as_list(state_event_ids)
  894. context = await self.state.compute_event_context(event, old_state=old_state)
  895. else:
  896. context = await self.state.compute_event_context(event)
  897. if requester:
  898. context.app_service = requester.app_service
  899. res, new_content = await self.third_party_event_rules.check_event_allowed(
  900. event, context
  901. )
  902. if res is False:
  903. logger.info(
  904. "Event %s forbidden by third-party rules",
  905. event,
  906. )
  907. raise SynapseError(
  908. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  909. )
  910. elif new_content is not None:
  911. # the third-party rules want to replace the event. We'll need to build a new
  912. # event.
  913. event, context = await self._rebuild_event_after_third_party_rules(
  914. new_content, event
  915. )
  916. self.validator.validate_new(event, self.config)
  917. await self._validate_event_relation(event)
  918. logger.debug("Created event %s", event.event_id)
  919. return event, context
  920. async def _validate_event_relation(self, event: EventBase) -> None:
  921. """
  922. Ensure the relation data on a new event is not bogus.
  923. Args:
  924. event: The event being created.
  925. Raises:
  926. SynapseError if the event is invalid.
  927. """
  928. relation = relation_from_event(event)
  929. if not relation:
  930. return
  931. parent_event = await self.store.get_event(relation.parent_id, allow_none=True)
  932. if parent_event:
  933. # And in the same room.
  934. if parent_event.room_id != event.room_id:
  935. raise SynapseError(400, "Relations must be in the same room")
  936. else:
  937. # There must be some reason that the client knows the event exists,
  938. # see if there are existing relations. If so, assume everything is fine.
  939. if not await self.store.event_is_target_of_relation(relation.parent_id):
  940. # Otherwise, the client can't know about the parent event!
  941. raise SynapseError(400, "Can't send relation to unknown event")
  942. # If this event is an annotation then we check that that the sender
  943. # can't annotate the same way twice (e.g. stops users from liking an
  944. # event multiple times).
  945. if relation.rel_type == RelationTypes.ANNOTATION:
  946. aggregation_key = relation.aggregation_key
  947. if aggregation_key is None:
  948. raise SynapseError(400, "Missing aggregation key")
  949. if len(aggregation_key) > 500:
  950. raise SynapseError(400, "Aggregation key is too long")
  951. already_exists = await self.store.has_user_annotated_event(
  952. relation.parent_id, event.type, aggregation_key, event.sender
  953. )
  954. if already_exists:
  955. raise SynapseError(400, "Can't send same reaction twice")
  956. # Don't attempt to start a thread if the parent event is a relation.
  957. elif relation.rel_type == RelationTypes.THREAD:
  958. if await self.store.event_includes_relation(relation.parent_id):
  959. raise SynapseError(
  960. 400, "Cannot start threads from an event with a relation"
  961. )
  962. @measure_func("handle_new_client_event")
  963. async def handle_new_client_event(
  964. self,
  965. requester: Requester,
  966. event: EventBase,
  967. context: EventContext,
  968. ratelimit: bool = True,
  969. extra_users: Optional[List[UserID]] = None,
  970. ignore_shadow_ban: bool = False,
  971. ) -> EventBase:
  972. """Processes a new event.
  973. This includes deduplicating, checking auth, persisting,
  974. notifying users, sending to remote servers, etc.
  975. If called from a worker will hit out to the master process for final
  976. processing.
  977. Args:
  978. requester
  979. event
  980. context
  981. ratelimit
  982. extra_users: Any extra users to notify about event
  983. ignore_shadow_ban: True if shadow-banned users should be allowed to
  984. send this event.
  985. Return:
  986. If the event was deduplicated, the previous, duplicate, event. Otherwise,
  987. `event`.
  988. Raises:
  989. ShadowBanError if the requester has been shadow-banned.
  990. """
  991. extra_users = extra_users or []
  992. # we don't apply shadow-banning to membership events here. Invites are blocked
  993. # higher up the stack, and we allow shadow-banned users to send join and leave
  994. # events as normal.
  995. if (
  996. event.type != EventTypes.Member
  997. and not ignore_shadow_ban
  998. and requester.shadow_banned
  999. ):
  1000. # We randomly sleep a bit just to annoy the requester.
  1001. await self.clock.sleep(random.randint(1, 10))
  1002. raise ShadowBanError()
  1003. if event.is_state():
  1004. prev_event = await self.deduplicate_state_event(event, context)
  1005. if prev_event is not None:
  1006. logger.info(
  1007. "Not bothering to persist state event %s duplicated by %s",
  1008. event.event_id,
  1009. prev_event.event_id,
  1010. )
  1011. return prev_event
  1012. if event.is_state() and (event.type, event.state_key) == (
  1013. EventTypes.Create,
  1014. "",
  1015. ):
  1016. room_version_id = event.content.get(
  1017. "room_version", RoomVersions.V1.identifier
  1018. )
  1019. maybe_room_version_obj = KNOWN_ROOM_VERSIONS.get(room_version_id)
  1020. if not maybe_room_version_obj:
  1021. raise UnsupportedRoomVersionError(
  1022. "Attempt to create a room with unsupported room version %s"
  1023. % (room_version_id,)
  1024. )
  1025. room_version_obj = maybe_room_version_obj
  1026. else:
  1027. room_version_obj = await self.store.get_room_version(event.room_id)
  1028. if event.internal_metadata.is_out_of_band_membership():
  1029. # the only sort of out-of-band-membership events we expect to see here are
  1030. # invite rejections and rescinded knocks that we have generated ourselves.
  1031. assert event.type == EventTypes.Member
  1032. assert event.content["membership"] == Membership.LEAVE
  1033. else:
  1034. try:
  1035. validate_event_for_room_version(room_version_obj, event)
  1036. await self._event_auth_handler.check_auth_rules_from_context(
  1037. room_version_obj, event, context
  1038. )
  1039. except AuthError as err:
  1040. logger.warning("Denying new event %r because %s", event, err)
  1041. raise err
  1042. # Ensure that we can round trip before trying to persist in db
  1043. try:
  1044. dump = json_encoder.encode(event.content)
  1045. json_decoder.decode(dump)
  1046. except Exception:
  1047. logger.exception("Failed to encode content: %r", event.content)
  1048. raise
  1049. # We now persist the event (and update the cache in parallel, since we
  1050. # don't want to block on it).
  1051. result, _ = await make_deferred_yieldable(
  1052. gather_results(
  1053. (
  1054. run_in_background(
  1055. self._persist_event,
  1056. requester=requester,
  1057. event=event,
  1058. context=context,
  1059. ratelimit=ratelimit,
  1060. extra_users=extra_users,
  1061. ),
  1062. run_in_background(
  1063. self.cache_joined_hosts_for_event, event, context
  1064. ).addErrback(log_failure, "cache_joined_hosts_for_event failed"),
  1065. ),
  1066. consumeErrors=True,
  1067. )
  1068. ).addErrback(unwrapFirstError)
  1069. return result
  1070. async def _persist_event(
  1071. self,
  1072. requester: Requester,
  1073. event: EventBase,
  1074. context: EventContext,
  1075. ratelimit: bool = True,
  1076. extra_users: Optional[List[UserID]] = None,
  1077. ) -> EventBase:
  1078. """Actually persists the event. Should only be called by
  1079. `handle_new_client_event`, and see its docstring for documentation of
  1080. the arguments.
  1081. """
  1082. # Skip push notification actions for historical messages
  1083. # because we don't want to notify people about old history back in time.
  1084. # The historical messages also do not have the proper `context.current_state_ids`
  1085. # and `state_groups` because they have `prev_events` that aren't persisted yet
  1086. # (historical messages persisted in reverse-chronological order).
  1087. if not event.internal_metadata.is_historical():
  1088. await self._bulk_push_rule_evaluator.action_for_event_by_user(
  1089. event, context
  1090. )
  1091. try:
  1092. # If we're a worker we need to hit out to the master.
  1093. writer_instance = self._events_shard_config.get_instance(event.room_id)
  1094. if writer_instance != self._instance_name:
  1095. result = await self.send_event(
  1096. instance_name=writer_instance,
  1097. event_id=event.event_id,
  1098. store=self.store,
  1099. requester=requester,
  1100. event=event,
  1101. context=context,
  1102. ratelimit=ratelimit,
  1103. extra_users=extra_users,
  1104. )
  1105. stream_id = result["stream_id"]
  1106. event_id = result["event_id"]
  1107. if event_id != event.event_id:
  1108. # If we get a different event back then it means that its
  1109. # been de-duplicated, so we replace the given event with the
  1110. # one already persisted.
  1111. event = await self.store.get_event(event_id)
  1112. else:
  1113. # If we newly persisted the event then we need to update its
  1114. # stream_ordering entry manually (as it was persisted on
  1115. # another worker).
  1116. event.internal_metadata.stream_ordering = stream_id
  1117. return event
  1118. event = await self.persist_and_notify_client_event(
  1119. requester, event, context, ratelimit=ratelimit, extra_users=extra_users
  1120. )
  1121. return event
  1122. except Exception:
  1123. # Ensure that we actually remove the entries in the push actions
  1124. # staging area, if we calculated them.
  1125. await self.store.remove_push_actions_from_staging(event.event_id)
  1126. raise
  1127. async def cache_joined_hosts_for_event(
  1128. self, event: EventBase, context: EventContext
  1129. ) -> None:
  1130. """Precalculate the joined hosts at the event, when using Redis, so that
  1131. external federation senders don't have to recalculate it themselves.
  1132. """
  1133. if not self._external_cache.is_enabled():
  1134. return
  1135. # If external cache is enabled we should always have this.
  1136. assert self._external_cache_joined_hosts_updates is not None
  1137. # We actually store two mappings, event ID -> prev state group,
  1138. # state group -> joined hosts, which is much more space efficient
  1139. # than event ID -> joined hosts.
  1140. #
  1141. # Note: We have to cache event ID -> prev state group, as we don't
  1142. # store that in the DB.
  1143. #
  1144. # Note: We set the state group -> joined hosts cache if it hasn't been
  1145. # set for a while, so that the expiry time is reset.
  1146. state_entry = await self.state.resolve_state_groups_for_events(
  1147. event.room_id, event_ids=event.prev_event_ids()
  1148. )
  1149. if state_entry.state_group:
  1150. await self._external_cache.set(
  1151. "event_to_prev_state_group",
  1152. event.event_id,
  1153. state_entry.state_group,
  1154. expiry_ms=60 * 60 * 1000,
  1155. )
  1156. if state_entry.state_group in self._external_cache_joined_hosts_updates:
  1157. return
  1158. joined_hosts = await self.store.get_joined_hosts(event.room_id, state_entry)
  1159. # Note that the expiry times must be larger than the expiry time in
  1160. # _external_cache_joined_hosts_updates.
  1161. await self._external_cache.set(
  1162. "get_joined_hosts",
  1163. str(state_entry.state_group),
  1164. list(joined_hosts),
  1165. expiry_ms=60 * 60 * 1000,
  1166. )
  1167. self._external_cache_joined_hosts_updates[state_entry.state_group] = None
  1168. async def _validate_canonical_alias(
  1169. self,
  1170. directory_handler: DirectoryHandler,
  1171. room_alias_str: str,
  1172. expected_room_id: str,
  1173. ) -> None:
  1174. """
  1175. Ensure that the given room alias points to the expected room ID.
  1176. Args:
  1177. directory_handler: The directory handler object.
  1178. room_alias_str: The room alias to check.
  1179. expected_room_id: The room ID that the alias should point to.
  1180. """
  1181. room_alias = RoomAlias.from_string(room_alias_str)
  1182. try:
  1183. mapping = await directory_handler.get_association(room_alias)
  1184. except SynapseError as e:
  1185. # Turn M_NOT_FOUND errors into M_BAD_ALIAS errors.
  1186. if e.errcode == Codes.NOT_FOUND:
  1187. raise SynapseError(
  1188. 400,
  1189. "Room alias %s does not point to the room" % (room_alias_str,),
  1190. Codes.BAD_ALIAS,
  1191. )
  1192. raise
  1193. if mapping["room_id"] != expected_room_id:
  1194. raise SynapseError(
  1195. 400,
  1196. "Room alias %s does not point to the room" % (room_alias_str,),
  1197. Codes.BAD_ALIAS,
  1198. )
  1199. async def persist_and_notify_client_event(
  1200. self,
  1201. requester: Requester,
  1202. event: EventBase,
  1203. context: EventContext,
  1204. ratelimit: bool = True,
  1205. extra_users: Optional[List[UserID]] = None,
  1206. ) -> EventBase:
  1207. """Called when we have fully built the event, have already
  1208. calculated the push actions for the event, and checked auth.
  1209. This should only be run on the instance in charge of persisting events.
  1210. Returns:
  1211. The persisted event. This may be different than the given event if
  1212. it was de-duplicated (e.g. because we had already persisted an
  1213. event with the same transaction ID.)
  1214. """
  1215. extra_users = extra_users or []
  1216. assert self.storage.persistence is not None
  1217. assert self._events_shard_config.should_handle(
  1218. self._instance_name, event.room_id
  1219. )
  1220. if ratelimit:
  1221. # We check if this is a room admin redacting an event so that we
  1222. # can apply different ratelimiting. We do this by simply checking
  1223. # it's not a self-redaction (to avoid having to look up whether the
  1224. # user is actually admin or not).
  1225. is_admin_redaction = False
  1226. if event.type == EventTypes.Redaction:
  1227. assert event.redacts is not None
  1228. original_event = await self.store.get_event(
  1229. event.redacts,
  1230. redact_behaviour=EventRedactBehaviour.as_is,
  1231. get_prev_content=False,
  1232. allow_rejected=False,
  1233. allow_none=True,
  1234. )
  1235. is_admin_redaction = bool(
  1236. original_event and event.sender != original_event.sender
  1237. )
  1238. await self.request_ratelimiter.ratelimit(
  1239. requester, is_admin_redaction=is_admin_redaction
  1240. )
  1241. await self._maybe_kick_guest_users(event, context)
  1242. if event.type == EventTypes.CanonicalAlias:
  1243. # Validate a newly added alias or newly added alt_aliases.
  1244. original_alias = None
  1245. original_alt_aliases: object = []
  1246. original_event_id = event.unsigned.get("replaces_state")
  1247. if original_event_id:
  1248. original_event = await self.store.get_event(original_event_id)
  1249. if original_event:
  1250. original_alias = original_event.content.get("alias", None)
  1251. original_alt_aliases = original_event.content.get("alt_aliases", [])
  1252. # Check the alias is currently valid (if it has changed).
  1253. room_alias_str = event.content.get("alias", None)
  1254. directory_handler = self.hs.get_directory_handler()
  1255. if room_alias_str and room_alias_str != original_alias:
  1256. await self._validate_canonical_alias(
  1257. directory_handler, room_alias_str, event.room_id
  1258. )
  1259. # Check that alt_aliases is the proper form.
  1260. alt_aliases = event.content.get("alt_aliases", [])
  1261. if not isinstance(alt_aliases, (list, tuple)):
  1262. raise SynapseError(
  1263. 400, "The alt_aliases property must be a list.", Codes.INVALID_PARAM
  1264. )
  1265. # If the old version of alt_aliases is of an unknown form,
  1266. # completely replace it.
  1267. if not isinstance(original_alt_aliases, (list, tuple)):
  1268. # TODO: check that the original_alt_aliases' entries are all strings
  1269. original_alt_aliases = []
  1270. # Check that each alias is currently valid.
  1271. new_alt_aliases = set(alt_aliases) - set(original_alt_aliases)
  1272. if new_alt_aliases:
  1273. for alias_str in new_alt_aliases:
  1274. await self._validate_canonical_alias(
  1275. directory_handler, alias_str, event.room_id
  1276. )
  1277. federation_handler = self.hs.get_federation_handler()
  1278. if event.type == EventTypes.Member:
  1279. if event.content["membership"] == Membership.INVITE:
  1280. event.unsigned[
  1281. "invite_room_state"
  1282. ] = await self.store.get_stripped_room_state_from_event_context(
  1283. context,
  1284. self.room_prejoin_state_types,
  1285. membership_user_id=event.sender,
  1286. )
  1287. invitee = UserID.from_string(event.state_key)
  1288. if not self.hs.is_mine(invitee):
  1289. # TODO: Can we add signature from remote server in a nicer
  1290. # way? If we have been invited by a remote server, we need
  1291. # to get them to sign the event.
  1292. returned_invite = await federation_handler.send_invite(
  1293. invitee.domain, event
  1294. )
  1295. event.unsigned.pop("room_state", None)
  1296. # TODO: Make sure the signatures actually are correct.
  1297. event.signatures.update(returned_invite.signatures)
  1298. if event.content["membership"] == Membership.KNOCK:
  1299. event.unsigned[
  1300. "knock_room_state"
  1301. ] = await self.store.get_stripped_room_state_from_event_context(
  1302. context,
  1303. self.room_prejoin_state_types,
  1304. )
  1305. if event.type == EventTypes.Redaction:
  1306. assert event.redacts is not None
  1307. original_event = await self.store.get_event(
  1308. event.redacts,
  1309. redact_behaviour=EventRedactBehaviour.as_is,
  1310. get_prev_content=False,
  1311. allow_rejected=False,
  1312. allow_none=True,
  1313. )
  1314. room_version = await self.store.get_room_version_id(event.room_id)
  1315. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1316. # we can make some additional checks now if we have the original event.
  1317. if original_event:
  1318. if original_event.type == EventTypes.Create:
  1319. raise AuthError(403, "Redacting create events is not permitted")
  1320. if original_event.room_id != event.room_id:
  1321. raise SynapseError(400, "Cannot redact event from a different room")
  1322. if original_event.type == EventTypes.ServerACL:
  1323. raise AuthError(403, "Redacting server ACL events is not permitted")
  1324. # Add a little safety stop-gap to prevent people from trying to
  1325. # redact MSC2716 related events when they're in a room version
  1326. # which does not support it yet. We allow people to use MSC2716
  1327. # events in existing room versions but only from the room
  1328. # creator since it does not require any changes to the auth
  1329. # rules and in effect, the redaction algorithm . In the
  1330. # supported room version, we add the `historical` power level to
  1331. # auth the MSC2716 related events and adjust the redaction
  1332. # algorthim to keep the `historical` field around (redacting an
  1333. # event should only strip fields which don't affect the
  1334. # structural protocol level).
  1335. is_msc2716_event = (
  1336. original_event.type == EventTypes.MSC2716_INSERTION
  1337. or original_event.type == EventTypes.MSC2716_BATCH
  1338. or original_event.type == EventTypes.MSC2716_MARKER
  1339. )
  1340. if not room_version_obj.msc2716_historical and is_msc2716_event:
  1341. raise AuthError(
  1342. 403,
  1343. "Redacting MSC2716 events is not supported in this room version",
  1344. )
  1345. event_types = event_auth.auth_types_for_event(event.room_version, event)
  1346. prev_state_ids = await context.get_prev_state_ids(
  1347. StateFilter.from_types(event_types)
  1348. )
  1349. auth_events_ids = self._event_auth_handler.compute_auth_events(
  1350. event, prev_state_ids, for_verification=True
  1351. )
  1352. auth_events_map = await self.store.get_events(auth_events_ids)
  1353. auth_events = {(e.type, e.state_key): e for e in auth_events_map.values()}
  1354. if event_auth.check_redaction(
  1355. room_version_obj, event, auth_events=auth_events
  1356. ):
  1357. # this user doesn't have 'redact' rights, so we need to do some more
  1358. # checks on the original event. Let's start by checking the original
  1359. # event exists.
  1360. if not original_event:
  1361. raise NotFoundError("Could not find event %s" % (event.redacts,))
  1362. if event.user_id != original_event.user_id:
  1363. raise AuthError(403, "You don't have permission to redact events")
  1364. # all the checks are done.
  1365. event.internal_metadata.recheck_redaction = False
  1366. if event.type == EventTypes.Create:
  1367. prev_state_ids = await context.get_prev_state_ids()
  1368. if prev_state_ids:
  1369. raise AuthError(403, "Changing the room create event is forbidden")
  1370. if event.type == EventTypes.MSC2716_INSERTION:
  1371. room_version = await self.store.get_room_version_id(event.room_id)
  1372. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1373. create_event = await self.store.get_create_event_for_room(event.room_id)
  1374. room_creator = create_event.content.get(EventContentFields.ROOM_CREATOR)
  1375. # Only check an insertion event if the room version
  1376. # supports it or the event is from the room creator.
  1377. if room_version_obj.msc2716_historical or (
  1378. self.config.experimental.msc2716_enabled
  1379. and event.sender == room_creator
  1380. ):
  1381. next_batch_id = event.content.get(
  1382. EventContentFields.MSC2716_NEXT_BATCH_ID
  1383. )
  1384. conflicting_insertion_event_id = None
  1385. if next_batch_id:
  1386. conflicting_insertion_event_id = (
  1387. await self.store.get_insertion_event_id_by_batch_id(
  1388. event.room_id, next_batch_id
  1389. )
  1390. )
  1391. if conflicting_insertion_event_id is not None:
  1392. # The current insertion event that we're processing is invalid
  1393. # because an insertion event already exists in the room with the
  1394. # same next_batch_id. We can't allow multiple because the batch
  1395. # pointing will get weird, e.g. we can't determine which insertion
  1396. # event the batch event is pointing to.
  1397. raise SynapseError(
  1398. HTTPStatus.BAD_REQUEST,
  1399. "Another insertion event already exists with the same next_batch_id",
  1400. errcode=Codes.INVALID_PARAM,
  1401. )
  1402. # Mark any `m.historical` messages as backfilled so they don't appear
  1403. # in `/sync` and have the proper decrementing `stream_ordering` as we import
  1404. backfilled = False
  1405. if event.internal_metadata.is_historical():
  1406. backfilled = True
  1407. # Note that this returns the event that was persisted, which may not be
  1408. # the same as we passed in if it was deduplicated due transaction IDs.
  1409. (
  1410. event,
  1411. event_pos,
  1412. max_stream_token,
  1413. ) = await self.storage.persistence.persist_event(
  1414. event, context=context, backfilled=backfilled
  1415. )
  1416. if self._ephemeral_events_enabled:
  1417. # If there's an expiry timestamp on the event, schedule its expiry.
  1418. self._message_handler.maybe_schedule_expiry(event)
  1419. async def _notify() -> None:
  1420. try:
  1421. await self.notifier.on_new_room_event(
  1422. event, event_pos, max_stream_token, extra_users=extra_users
  1423. )
  1424. except Exception:
  1425. logger.exception(
  1426. "Error notifying about new room event %s",
  1427. event.event_id,
  1428. )
  1429. run_in_background(_notify)
  1430. if event.type == EventTypes.Message:
  1431. # We don't want to block sending messages on any presence code. This
  1432. # matters as sometimes presence code can take a while.
  1433. run_in_background(self._bump_active_time, requester.user)
  1434. return event
  1435. async def _maybe_kick_guest_users(
  1436. self, event: EventBase, context: EventContext
  1437. ) -> None:
  1438. if event.type != EventTypes.GuestAccess:
  1439. return
  1440. guest_access = event.content.get(EventContentFields.GUEST_ACCESS)
  1441. if guest_access == GuestAccess.CAN_JOIN:
  1442. return
  1443. current_state_ids = await context.get_current_state_ids()
  1444. # since this is a client-generated event, it cannot be an outlier and we must
  1445. # therefore have the state ids.
  1446. assert current_state_ids is not None
  1447. current_state_dict = await self.store.get_events(
  1448. list(current_state_ids.values())
  1449. )
  1450. current_state = list(current_state_dict.values())
  1451. logger.info("maybe_kick_guest_users %r", current_state)
  1452. await self.hs.get_room_member_handler().kick_guest_users(current_state)
  1453. async def _bump_active_time(self, user: UserID) -> None:
  1454. try:
  1455. presence = self.hs.get_presence_handler()
  1456. await presence.bump_presence_active_time(user)
  1457. except Exception:
  1458. logger.exception("Error bumping presence active time")
  1459. async def _send_dummy_events_to_fill_extremities(self) -> None:
  1460. """Background task to send dummy events into rooms that have a large
  1461. number of extremities
  1462. """
  1463. self._expire_rooms_to_exclude_from_dummy_event_insertion()
  1464. room_ids = await self.store.get_rooms_with_many_extremities(
  1465. min_count=self._dummy_events_threshold,
  1466. limit=5,
  1467. room_id_filter=self._rooms_to_exclude_from_dummy_event_insertion.keys(),
  1468. )
  1469. for room_id in room_ids:
  1470. dummy_event_sent = await self._send_dummy_event_for_room(room_id)
  1471. if not dummy_event_sent:
  1472. # Did not find a valid user in the room, so remove from future attempts
  1473. # Exclusion is time limited, so the room will be rechecked in the future
  1474. # dependent on _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY
  1475. logger.info(
  1476. "Failed to send dummy event into room %s. Will exclude it from "
  1477. "future attempts until cache expires" % (room_id,)
  1478. )
  1479. now = self.clock.time_msec()
  1480. self._rooms_to_exclude_from_dummy_event_insertion[room_id] = now
  1481. async def _send_dummy_event_for_room(self, room_id: str) -> bool:
  1482. """Attempt to send a dummy event for the given room.
  1483. Args:
  1484. room_id: room to try to send an event from
  1485. Returns:
  1486. True if a dummy event was successfully sent. False if no user was able
  1487. to send an event.
  1488. """
  1489. # For each room we need to find a joined member we can use to send
  1490. # the dummy event with.
  1491. latest_event_ids = await self.store.get_prev_events_for_room(room_id)
  1492. members = await self.state.get_current_users_in_room(
  1493. room_id, latest_event_ids=latest_event_ids
  1494. )
  1495. for user_id in members:
  1496. if not self.hs.is_mine_id(user_id):
  1497. continue
  1498. requester = create_requester(user_id, authenticated_entity=self.server_name)
  1499. try:
  1500. event, context = await self.create_event(
  1501. requester,
  1502. {
  1503. "type": EventTypes.Dummy,
  1504. "content": {},
  1505. "room_id": room_id,
  1506. "sender": user_id,
  1507. },
  1508. prev_event_ids=latest_event_ids,
  1509. )
  1510. event.internal_metadata.proactively_send = False
  1511. # Since this is a dummy-event it is OK if it is sent by a
  1512. # shadow-banned user.
  1513. await self.handle_new_client_event(
  1514. requester,
  1515. event,
  1516. context,
  1517. ratelimit=False,
  1518. ignore_shadow_ban=True,
  1519. )
  1520. return True
  1521. except AuthError:
  1522. logger.info(
  1523. "Failed to send dummy event into room %s for user %s due to "
  1524. "lack of power. Will try another user" % (room_id, user_id)
  1525. )
  1526. return False
  1527. def _expire_rooms_to_exclude_from_dummy_event_insertion(self) -> None:
  1528. expire_before = self.clock.time_msec() - _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY
  1529. to_expire = set()
  1530. for room_id, time in self._rooms_to_exclude_from_dummy_event_insertion.items():
  1531. if time < expire_before:
  1532. to_expire.add(room_id)
  1533. for room_id in to_expire:
  1534. logger.debug(
  1535. "Expiring room id %s from dummy event insertion exclusion cache",
  1536. room_id,
  1537. )
  1538. del self._rooms_to_exclude_from_dummy_event_insertion[room_id]
  1539. async def _rebuild_event_after_third_party_rules(
  1540. self, third_party_result: dict, original_event: EventBase
  1541. ) -> Tuple[EventBase, EventContext]:
  1542. # the third_party_event_rules want to replace the event.
  1543. # we do some basic checks, and then return the replacement event and context.
  1544. # Construct a new EventBuilder and validate it, which helps with the
  1545. # rest of these checks.
  1546. try:
  1547. builder = self.event_builder_factory.for_room_version(
  1548. original_event.room_version, third_party_result
  1549. )
  1550. self.validator.validate_builder(builder)
  1551. except SynapseError as e:
  1552. raise Exception(
  1553. "Third party rules module created an invalid event: " + e.msg,
  1554. )
  1555. immutable_fields = [
  1556. # changing the room is going to break things: we've already checked that the
  1557. # room exists, and are holding a concurrency limiter token for that room.
  1558. # Also, we might need to use a different room version.
  1559. "room_id",
  1560. # changing the type or state key might work, but we'd need to check that the
  1561. # calling functions aren't making assumptions about them.
  1562. "type",
  1563. "state_key",
  1564. ]
  1565. for k in immutable_fields:
  1566. if getattr(builder, k, None) != original_event.get(k):
  1567. raise Exception(
  1568. "Third party rules module created an invalid event: "
  1569. "cannot change field " + k
  1570. )
  1571. # check that the new sender belongs to this HS
  1572. if not self.hs.is_mine_id(builder.sender):
  1573. raise Exception(
  1574. "Third party rules module created an invalid event: "
  1575. "invalid sender " + builder.sender
  1576. )
  1577. # copy over the original internal metadata
  1578. for k, v in original_event.internal_metadata.get_dict().items():
  1579. setattr(builder.internal_metadata, k, v)
  1580. # modules can send new state events, so we re-calculate the auth events just in
  1581. # case.
  1582. prev_event_ids = await self.store.get_prev_events_for_room(builder.room_id)
  1583. event = await builder.build(
  1584. prev_event_ids=prev_event_ids,
  1585. auth_event_ids=None,
  1586. )
  1587. # we rebuild the event context, to be on the safe side. If nothing else,
  1588. # delta_ids might need an update.
  1589. context = await self.state.compute_event_context(event)
  1590. return event, context