Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

2132 rader
88 KiB

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