You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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