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.
 
 
 
 
 
 

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