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.
 
 
 
 
 
 

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