No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

2159 líneas
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. 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 = await 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 the device ID and the transaction ID in the event internal metadata.
  596. # This is useful to determine if we should echo the transaction_id in events.
  597. # See `synapse.events.utils.EventClientSerializer.serialize_event`
  598. if requester.device_id is not None:
  599. builder.internal_metadata.device_id = requester.device_id
  600. if txn_id is not None:
  601. builder.internal_metadata.txn_id = txn_id
  602. builder.internal_metadata.outlier = outlier
  603. event, unpersisted_context = await self.create_new_client_event(
  604. builder=builder,
  605. requester=requester,
  606. allow_no_prev_events=allow_no_prev_events,
  607. prev_event_ids=prev_event_ids,
  608. auth_event_ids=auth_event_ids,
  609. state_event_ids=state_event_ids,
  610. depth=depth,
  611. state_map=state_map,
  612. for_batch=for_batch,
  613. current_state_group=current_state_group,
  614. )
  615. # In an ideal world we wouldn't need the second part of this condition. However,
  616. # this behaviour isn't spec'd yet, meaning we should be able to deactivate this
  617. # behaviour. Another reason is that this code is also evaluated each time a new
  618. # m.room.aliases event is created, which includes hitting a /directory route.
  619. # Therefore not including this condition here would render the similar one in
  620. # synapse.handlers.directory pointless.
  621. if builder.type == EventTypes.Aliases and self.require_membership_for_aliases:
  622. # Ideally we'd do the membership check in event_auth.check(), which
  623. # describes a spec'd algorithm for authenticating events received over
  624. # federation as well as those created locally. As of room v3, aliases events
  625. # can be created by users that are not in the room, therefore we have to
  626. # tolerate them in event_auth.check().
  627. if for_batch:
  628. assert state_map is not None
  629. prev_event_id = state_map.get((EventTypes.Member, event.sender))
  630. else:
  631. prev_state_ids = await unpersisted_context.get_prev_state_ids(
  632. StateFilter.from_types([(EventTypes.Member, event.sender)])
  633. )
  634. prev_event_id = prev_state_ids.get((EventTypes.Member, event.sender))
  635. prev_event = (
  636. await self.store.get_event(prev_event_id, allow_none=True)
  637. if prev_event_id
  638. else None
  639. )
  640. if not prev_event or prev_event.membership != Membership.JOIN:
  641. logger.warning(
  642. (
  643. "Attempt to send `m.room.aliases` in room %s by user %s but"
  644. " membership is %s"
  645. ),
  646. event.room_id,
  647. event.sender,
  648. prev_event.membership if prev_event else None,
  649. )
  650. raise AuthError(
  651. 403, "You must be in the room to create an alias for it"
  652. )
  653. self.validator.validate_new(event, self.config)
  654. return event, unpersisted_context
  655. async def _is_exempt_from_privacy_policy(
  656. self, builder: EventBuilder, requester: Requester
  657. ) -> bool:
  658. """ "Determine if an event to be sent is exempt from having to consent
  659. to the privacy policy
  660. Args:
  661. builder: event being created
  662. requester: user requesting this event
  663. Returns:
  664. true if the event can be sent without the user consenting
  665. """
  666. # the only thing the user can do is join the server notices room.
  667. if builder.type == EventTypes.Member:
  668. membership = builder.content.get("membership", None)
  669. if membership == Membership.JOIN:
  670. return await self.store.is_server_notice_room(builder.room_id)
  671. elif membership == Membership.LEAVE:
  672. # the user is always allowed to leave (but not kick people)
  673. return builder.state_key == requester.user.to_string()
  674. return False
  675. async def assert_accepted_privacy_policy(self, requester: Requester) -> None:
  676. """Check if a user has accepted the privacy policy
  677. Called when the given user is about to do something that requires
  678. privacy consent. We see if the user is exempt and otherwise check that
  679. they have given consent. If they have not, a ConsentNotGiven error is
  680. raised.
  681. Args:
  682. requester: The user making the request
  683. Returns:
  684. Returns normally if the user has consented or is exempt
  685. Raises:
  686. ConsentNotGivenError: if the user has not given consent yet
  687. """
  688. if self._block_events_without_consent_error is None:
  689. return
  690. # exempt AS users from needing consent
  691. if requester.app_service is not None:
  692. return
  693. user_id = requester.authenticated_entity
  694. if not user_id.startswith("@"):
  695. # The authenticated entity might not be a user, e.g. if it's the
  696. # server puppetting the user.
  697. return
  698. user = UserID.from_string(user_id)
  699. # exempt the system notices user
  700. if (
  701. self.config.servernotices.server_notices_mxid is not None
  702. and user_id == self.config.servernotices.server_notices_mxid
  703. ):
  704. return
  705. u = await self.store.get_user_by_id(user_id)
  706. assert u is not None
  707. if u.user_type in (UserTypes.SUPPORT, UserTypes.BOT):
  708. # support and bot users are not required to consent
  709. return
  710. if u.appservice_id is not None:
  711. # users registered by an appservice are exempt
  712. return
  713. if u.consent_version == self.config.consent.user_consent_version:
  714. return
  715. consent_uri = self._consent_uri_builder.build_user_consent_uri(user.localpart)
  716. msg = self._block_events_without_consent_error % {"consent_uri": consent_uri}
  717. raise ConsentNotGivenError(msg=msg, consent_uri=consent_uri)
  718. async def deduplicate_state_event(
  719. self, event: EventBase, context: EventContext
  720. ) -> Optional[EventBase]:
  721. """
  722. Checks whether event is in the latest resolved state in context.
  723. Args:
  724. event: The event to check for duplication.
  725. context: The event context.
  726. Returns:
  727. The previous version of the event is returned, if it is found in the
  728. event context. Otherwise, None is returned.
  729. """
  730. if event.internal_metadata.is_outlier():
  731. # This can happen due to out of band memberships
  732. return None
  733. prev_state_ids = await context.get_prev_state_ids(
  734. StateFilter.from_types([(event.type, event.state_key)])
  735. )
  736. prev_event_id = prev_state_ids.get((event.type, event.state_key))
  737. if not prev_event_id:
  738. return None
  739. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  740. if not prev_event:
  741. return None
  742. if prev_event and event.user_id == prev_event.user_id:
  743. prev_content = encode_canonical_json(prev_event.content)
  744. next_content = encode_canonical_json(event.content)
  745. if prev_content == next_content:
  746. return prev_event
  747. return None
  748. async def get_event_id_from_transaction(
  749. self,
  750. requester: Requester,
  751. txn_id: str,
  752. room_id: str,
  753. ) -> Optional[str]:
  754. """For the given transaction ID and room ID, check if there is a matching event ID.
  755. Args:
  756. requester: The requester making the request in the context of which we want
  757. to fetch the event.
  758. txn_id: The transaction ID.
  759. room_id: The room ID.
  760. Returns:
  761. An event ID if one could be found, None otherwise.
  762. """
  763. existing_event_id = None
  764. # According to the spec, transactions are scoped to a user's device ID.
  765. if requester.device_id:
  766. existing_event_id = (
  767. await self.store.get_event_id_from_transaction_id_and_device_id(
  768. room_id,
  769. requester.user.to_string(),
  770. requester.device_id,
  771. txn_id,
  772. )
  773. )
  774. if existing_event_id:
  775. return existing_event_id
  776. return existing_event_id
  777. async def get_event_from_transaction(
  778. self,
  779. requester: Requester,
  780. txn_id: str,
  781. room_id: str,
  782. ) -> Optional[EventBase]:
  783. """For the given transaction ID and room ID, check if there is a matching event.
  784. If so, fetch it and return it.
  785. Args:
  786. requester: The requester making the request in the context of which we want
  787. to fetch the event.
  788. txn_id: The transaction ID.
  789. room_id: The room ID.
  790. Returns:
  791. An event if one could be found, None otherwise.
  792. """
  793. existing_event_id = await self.get_event_id_from_transaction(
  794. requester, txn_id, room_id
  795. )
  796. if existing_event_id:
  797. return await self.store.get_event(existing_event_id)
  798. return None
  799. async def create_and_send_nonmember_event(
  800. self,
  801. requester: Requester,
  802. event_dict: dict,
  803. allow_no_prev_events: bool = False,
  804. prev_event_ids: Optional[List[str]] = None,
  805. state_event_ids: Optional[List[str]] = None,
  806. ratelimit: bool = True,
  807. txn_id: Optional[str] = None,
  808. ignore_shadow_ban: bool = False,
  809. outlier: bool = False,
  810. depth: Optional[int] = None,
  811. ) -> Tuple[EventBase, int]:
  812. """
  813. Creates an event, then sends it.
  814. See self.create_event and self.handle_new_client_event.
  815. Args:
  816. requester: The requester sending the event.
  817. event_dict: An entire event.
  818. allow_no_prev_events: Whether to allow this event to be created an empty
  819. list of prev_events. Normally this is prohibited just because most
  820. events should have a prev_event and we should only use this in special
  821. cases (previously useful for MSC2716).
  822. prev_event_ids:
  823. The event IDs to use as the prev events.
  824. Should normally be left as None to automatically request them
  825. from the database.
  826. state_event_ids:
  827. The full state at a given event. This was previously used particularly
  828. by the MSC2716 /batch_send endpoint. This should normally be left as
  829. None, which will cause the auth_event_ids to be calculated based on the
  830. room state at the prev_events.
  831. ratelimit: Whether to rate limit this send.
  832. txn_id: The transaction ID.
  833. ignore_shadow_ban: True if shadow-banned users should be allowed to
  834. send this event.
  835. outlier: Indicates whether the event is an `outlier`, i.e. if
  836. it's from an arbitrary point and floating in the DAG as
  837. opposed to being inline with the current DAG.
  838. depth: Override the depth used to order the event in the DAG.
  839. Should normally be set to None, which will cause the depth to be calculated
  840. based on the prev_events.
  841. Returns:
  842. The event, and its stream ordering (if deduplication happened,
  843. the previous, duplicate event).
  844. Raises:
  845. ShadowBanError if the requester has been shadow-banned.
  846. """
  847. if event_dict["type"] == EventTypes.Member:
  848. raise SynapseError(
  849. 500, "Tried to send member event through non-member codepath"
  850. )
  851. if not ignore_shadow_ban and requester.shadow_banned:
  852. # We randomly sleep a bit just to annoy the requester.
  853. await self.clock.sleep(random.randint(1, 10))
  854. raise ShadowBanError()
  855. if ratelimit:
  856. room_id = event_dict["room_id"]
  857. try:
  858. room_version = await self.store.get_room_version(room_id)
  859. except NotFoundError:
  860. # The room doesn't exist.
  861. raise AuthError(403, f"User {requester.user} not in room {room_id}")
  862. if room_version.updated_redaction_rules:
  863. redacts = event_dict["content"].get("redacts")
  864. else:
  865. redacts = event_dict.get("redacts")
  866. is_admin_redaction = await self.is_admin_redaction(
  867. event_type=event_dict["type"],
  868. sender=event_dict["sender"],
  869. redacts=redacts,
  870. )
  871. await self.request_ratelimiter.ratelimit(
  872. requester, is_admin_redaction=is_admin_redaction, update=False
  873. )
  874. # We limit the number of concurrent event sends in a room so that we
  875. # don't fork the DAG too much. If we don't limit then we can end up in
  876. # a situation where event persistence can't keep up, causing
  877. # extremities to pile up, which in turn leads to state resolution
  878. # taking longer.
  879. room_id = event_dict["room_id"]
  880. async with self.limiter.queue(room_id):
  881. if txn_id:
  882. event = await self.get_event_from_transaction(
  883. requester, txn_id, room_id
  884. )
  885. if event:
  886. # we know it was persisted, so must have a stream ordering
  887. assert event.internal_metadata.stream_ordering
  888. return (
  889. event,
  890. event.internal_metadata.stream_ordering,
  891. )
  892. async with self._worker_lock_handler.acquire_read_write_lock(
  893. NEW_EVENT_DURING_PURGE_LOCK_NAME, room_id, write=False
  894. ):
  895. return await self._create_and_send_nonmember_event_locked(
  896. requester=requester,
  897. event_dict=event_dict,
  898. allow_no_prev_events=allow_no_prev_events,
  899. prev_event_ids=prev_event_ids,
  900. state_event_ids=state_event_ids,
  901. ratelimit=ratelimit,
  902. txn_id=txn_id,
  903. ignore_shadow_ban=ignore_shadow_ban,
  904. outlier=outlier,
  905. depth=depth,
  906. )
  907. async def _create_and_send_nonmember_event_locked(
  908. self,
  909. requester: Requester,
  910. event_dict: dict,
  911. allow_no_prev_events: bool = False,
  912. prev_event_ids: Optional[List[str]] = None,
  913. state_event_ids: Optional[List[str]] = None,
  914. ratelimit: bool = True,
  915. txn_id: Optional[str] = None,
  916. ignore_shadow_ban: bool = False,
  917. outlier: bool = False,
  918. depth: Optional[int] = None,
  919. ) -> Tuple[EventBase, int]:
  920. room_id = event_dict["room_id"]
  921. # If we don't have any prev event IDs specified then we need to
  922. # check that the host is in the room (as otherwise populating the
  923. # prev events will fail), at which point we may as well check the
  924. # local user is in the room.
  925. if not prev_event_ids:
  926. user_id = requester.user.to_string()
  927. is_user_in_room = await self.store.check_local_user_in_room(
  928. user_id, room_id
  929. )
  930. if not is_user_in_room:
  931. raise AuthError(403, f"User {user_id} not in room {room_id}")
  932. # Try several times, it could fail with PartialStateConflictError
  933. # in handle_new_client_event, cf comment in except block.
  934. max_retries = 5
  935. for i in range(max_retries):
  936. try:
  937. event, unpersisted_context = await self.create_event(
  938. requester,
  939. event_dict,
  940. txn_id=txn_id,
  941. allow_no_prev_events=allow_no_prev_events,
  942. prev_event_ids=prev_event_ids,
  943. state_event_ids=state_event_ids,
  944. outlier=outlier,
  945. depth=depth,
  946. )
  947. context = await unpersisted_context.persist(event)
  948. assert self.hs.is_mine_id(event.sender), "User must be our own: %s" % (
  949. event.sender,
  950. )
  951. spam_check_result = (
  952. await self._spam_checker_module_callbacks.check_event_for_spam(
  953. event
  954. )
  955. )
  956. if spam_check_result != self._spam_checker_module_callbacks.NOT_SPAM:
  957. if isinstance(spam_check_result, tuple):
  958. try:
  959. [code, dict] = spam_check_result
  960. raise SynapseError(
  961. 403,
  962. "This message had been rejected as probable spam",
  963. code,
  964. dict,
  965. )
  966. except ValueError:
  967. logger.error(
  968. "Spam-check module returned invalid error value. Expecting [code, dict], got %s",
  969. spam_check_result,
  970. )
  971. raise SynapseError(
  972. 403,
  973. "This message has been rejected as probable spam",
  974. Codes.FORBIDDEN,
  975. )
  976. # Backwards compatibility: if the return value is not an error code, it
  977. # means the module returned an error message to be included in the
  978. # SynapseError (which is now deprecated).
  979. raise SynapseError(
  980. 403,
  981. spam_check_result,
  982. Codes.FORBIDDEN,
  983. )
  984. ev = await self.handle_new_client_event(
  985. requester=requester,
  986. events_and_context=[(event, context)],
  987. ratelimit=ratelimit,
  988. ignore_shadow_ban=ignore_shadow_ban,
  989. )
  990. break
  991. except PartialStateConflictError as e:
  992. # Persisting couldn't happen because the room got un-partial stated
  993. # in the meantime and context needs to be recomputed, so let's do so.
  994. if i == max_retries - 1:
  995. raise e
  996. # we know it was persisted, so must have a stream ordering
  997. assert ev.internal_metadata.stream_ordering
  998. return ev, ev.internal_metadata.stream_ordering
  999. @measure_func("create_new_client_event")
  1000. async def create_new_client_event(
  1001. self,
  1002. builder: EventBuilder,
  1003. requester: Optional[Requester] = None,
  1004. allow_no_prev_events: bool = False,
  1005. prev_event_ids: Optional[List[str]] = None,
  1006. auth_event_ids: Optional[List[str]] = None,
  1007. state_event_ids: Optional[List[str]] = None,
  1008. depth: Optional[int] = None,
  1009. state_map: Optional[StateMap[str]] = None,
  1010. for_batch: bool = False,
  1011. current_state_group: Optional[int] = None,
  1012. ) -> Tuple[EventBase, UnpersistedEventContextBase]:
  1013. """Create a new event for a local client. If bool for_batch is true, will
  1014. create an event using the prev_event_ids, and will create an event context for
  1015. the event using the parameters state_map and current_state_group, thus these parameters
  1016. must be provided in this case if for_batch is True. The subsequently created event
  1017. and context are suitable for being batched up and bulk persisted to the database
  1018. with other similarly created events. Note that this returns an UnpersistedEventContext,
  1019. which must be converted to an EventContext before it can be sent to the DB.
  1020. Args:
  1021. builder:
  1022. requester:
  1023. allow_no_prev_events: Whether to allow this event to be created an empty
  1024. list of prev_events. Normally this is prohibited just because most
  1025. events should have a prev_event and we should only use this in special
  1026. cases (previously useful for MSC2716).
  1027. prev_event_ids:
  1028. the forward extremities to use as the prev_events for the
  1029. new event.
  1030. If None, they will be requested from the database.
  1031. auth_event_ids:
  1032. The event ids to use as the auth_events for the new event.
  1033. Should normally be left as None, which will cause them to be calculated
  1034. based on the room state at the prev_events.
  1035. state_event_ids:
  1036. The full state at a given event. This was previously used particularly
  1037. by the MSC2716 /batch_send endpoint. This should normally be left as
  1038. None, which will cause the auth_event_ids to be calculated based on the
  1039. room state at the prev_events.
  1040. depth: Override the depth used to order the event in the DAG.
  1041. Should normally be set to None, which will cause the depth to be calculated
  1042. based on the prev_events.
  1043. state_map: A state map of previously created events, used only when creating events
  1044. for batch persisting
  1045. for_batch: whether the event is being created for batch persisting to the db
  1046. current_state_group: the current state group, used only for creating events for
  1047. batch persisting
  1048. Returns:
  1049. Tuple of created event, UnpersistedEventContext
  1050. """
  1051. # Strip down the state_event_ids to only what we need to auth the event.
  1052. # For example, we don't need extra m.room.member that don't match event.sender
  1053. if state_event_ids is not None:
  1054. # Do a quick check to make sure that prev_event_ids is present to
  1055. # make the type-checking around `builder.build` happy.
  1056. # prev_event_ids could be an empty array though.
  1057. assert prev_event_ids is not None
  1058. temp_event = await builder.build(
  1059. prev_event_ids=prev_event_ids,
  1060. auth_event_ids=state_event_ids,
  1061. depth=depth,
  1062. )
  1063. state_events = await self.store.get_events_as_list(state_event_ids)
  1064. # Create a StateMap[str]
  1065. current_state_ids = {
  1066. (e.type, e.state_key): e.event_id for e in state_events
  1067. }
  1068. # Actually strip down and only use the necessary auth events
  1069. auth_event_ids = self._event_auth_handler.compute_auth_events(
  1070. event=temp_event,
  1071. current_state_ids=current_state_ids,
  1072. for_verification=False,
  1073. )
  1074. if prev_event_ids is not None:
  1075. assert (
  1076. len(prev_event_ids) <= 10
  1077. ), "Attempting to create an event with %i prev_events" % (
  1078. len(prev_event_ids),
  1079. )
  1080. else:
  1081. prev_event_ids = await self.store.get_prev_events_for_room(builder.room_id)
  1082. # Do a quick sanity check here, rather than waiting until we've created the
  1083. # event and then try to auth it (which fails with a somewhat confusing "No
  1084. # create event in auth events")
  1085. if allow_no_prev_events:
  1086. # We allow events with no `prev_events` but it better have some `auth_events`
  1087. assert (
  1088. builder.type == EventTypes.Create
  1089. # Allow an event to have empty list of prev_event_ids
  1090. # only if it has auth_event_ids.
  1091. or auth_event_ids
  1092. ), "Attempting to create a non-m.room.create event with no prev_events or auth_event_ids"
  1093. else:
  1094. # we now ought to have some prev_events (unless it's a create event).
  1095. assert (
  1096. builder.type == EventTypes.Create or prev_event_ids
  1097. ), "Attempting to create a non-m.room.create event with no prev_events"
  1098. if for_batch:
  1099. assert prev_event_ids is not None
  1100. assert state_map is not None
  1101. auth_ids = self._event_auth_handler.compute_auth_events(builder, state_map)
  1102. event = await builder.build(
  1103. prev_event_ids=prev_event_ids, auth_event_ids=auth_ids, depth=depth
  1104. )
  1105. context: UnpersistedEventContextBase = (
  1106. await self.state.calculate_context_info(
  1107. event,
  1108. state_ids_before_event=state_map,
  1109. partial_state=False,
  1110. state_group_before_event=current_state_group,
  1111. )
  1112. )
  1113. else:
  1114. event = await builder.build(
  1115. prev_event_ids=prev_event_ids,
  1116. auth_event_ids=auth_event_ids,
  1117. depth=depth,
  1118. )
  1119. # Pass on the outlier property from the builder to the event
  1120. # after it is created
  1121. if builder.internal_metadata.outlier:
  1122. event.internal_metadata.outlier = True
  1123. context = EventContext.for_outlier(self._storage_controllers)
  1124. else:
  1125. context = await self.state.calculate_context_info(event)
  1126. if requester:
  1127. context.app_service = requester.app_service
  1128. res, new_content = await self._third_party_event_rules.check_event_allowed(
  1129. event, context
  1130. )
  1131. if res is False:
  1132. logger.info(
  1133. "Event %s forbidden by third-party rules",
  1134. event,
  1135. )
  1136. raise SynapseError(
  1137. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  1138. )
  1139. elif new_content is not None:
  1140. # the third-party rules want to replace the event. We'll need to build a new
  1141. # event.
  1142. event, context = await self._rebuild_event_after_third_party_rules(
  1143. new_content, event
  1144. )
  1145. self.validator.validate_new(event, self.config)
  1146. await self._validate_event_relation(event)
  1147. logger.debug("Created event %s", event.event_id)
  1148. return event, context
  1149. async def _validate_event_relation(self, event: EventBase) -> None:
  1150. """
  1151. Ensure the relation data on a new event is not bogus.
  1152. Args:
  1153. event: The event being created.
  1154. Raises:
  1155. SynapseError if the event is invalid.
  1156. """
  1157. relation = relation_from_event(event)
  1158. if not relation:
  1159. return
  1160. parent_event = await self.store.get_event(relation.parent_id, allow_none=True)
  1161. if parent_event:
  1162. # And in the same room.
  1163. if parent_event.room_id != event.room_id:
  1164. raise SynapseError(400, "Relations must be in the same room")
  1165. else:
  1166. # There must be some reason that the client knows the event exists,
  1167. # see if there are existing relations. If so, assume everything is fine.
  1168. if not await self.store.event_is_target_of_relation(relation.parent_id):
  1169. # Otherwise, the client can't know about the parent event!
  1170. raise SynapseError(400, "Can't send relation to unknown event")
  1171. # If this event is an annotation then we check that that the sender
  1172. # can't annotate the same way twice (e.g. stops users from liking an
  1173. # event multiple times).
  1174. if relation.rel_type == RelationTypes.ANNOTATION:
  1175. aggregation_key = relation.aggregation_key
  1176. if aggregation_key is None:
  1177. raise SynapseError(400, "Missing aggregation key")
  1178. if len(aggregation_key) > 500:
  1179. raise SynapseError(400, "Aggregation key is too long")
  1180. already_exists = await self.store.has_user_annotated_event(
  1181. relation.parent_id, event.type, aggregation_key, event.sender
  1182. )
  1183. if already_exists:
  1184. raise SynapseError(
  1185. 400,
  1186. "Can't send same reaction twice",
  1187. errcode=Codes.DUPLICATE_ANNOTATION,
  1188. )
  1189. # Don't attempt to start a thread if the parent event is a relation.
  1190. elif relation.rel_type == RelationTypes.THREAD:
  1191. if await self.store.event_includes_relation(relation.parent_id):
  1192. raise SynapseError(
  1193. 400, "Cannot start threads from an event with a relation"
  1194. )
  1195. @measure_func("handle_new_client_event")
  1196. async def handle_new_client_event(
  1197. self,
  1198. requester: Requester,
  1199. events_and_context: List[Tuple[EventBase, EventContext]],
  1200. ratelimit: bool = True,
  1201. extra_users: Optional[List[UserID]] = None,
  1202. ignore_shadow_ban: bool = False,
  1203. ) -> EventBase:
  1204. """Processes new events. Please note that if batch persisting events, an error in
  1205. handling any one of these events will result in all of the events being dropped.
  1206. This includes deduplicating, checking auth, persisting,
  1207. notifying users, sending to remote servers, etc.
  1208. If called from a worker will hit out to the master process for final
  1209. processing.
  1210. Args:
  1211. requester
  1212. events_and_context: A list of one or more tuples of event, context to be persisted
  1213. ratelimit
  1214. extra_users: Any extra users to notify about event
  1215. ignore_shadow_ban: True if shadow-banned users should be allowed to
  1216. send this event.
  1217. Return:
  1218. If the event was deduplicated, the previous, duplicate, event. Otherwise,
  1219. `event`.
  1220. Raises:
  1221. ShadowBanError if the requester has been shadow-banned.
  1222. PartialStateConflictError if attempting to persist a partial state event in
  1223. a room that has been un-partial stated.
  1224. """
  1225. extra_users = extra_users or []
  1226. for event, context in events_and_context:
  1227. # we don't apply shadow-banning to membership events here. Invites are blocked
  1228. # higher up the stack, and we allow shadow-banned users to send join and leave
  1229. # events as normal.
  1230. if (
  1231. event.type != EventTypes.Member
  1232. and not ignore_shadow_ban
  1233. and requester.shadow_banned
  1234. ):
  1235. # We randomly sleep a bit just to annoy the requester.
  1236. await self.clock.sleep(random.randint(1, 10))
  1237. raise ShadowBanError()
  1238. if event.is_state():
  1239. prev_event = await self.deduplicate_state_event(event, context)
  1240. if prev_event is not None:
  1241. logger.info(
  1242. "Not bothering to persist state event %s duplicated by %s",
  1243. event.event_id,
  1244. prev_event.event_id,
  1245. )
  1246. return prev_event
  1247. if event.internal_metadata.is_out_of_band_membership():
  1248. # the only sort of out-of-band-membership events we expect to see here are
  1249. # invite rejections and rescinded knocks that we have generated ourselves.
  1250. assert event.type == EventTypes.Member
  1251. assert event.content["membership"] == Membership.LEAVE
  1252. else:
  1253. try:
  1254. validate_event_for_room_version(event)
  1255. # If we are persisting a batch of events the event(s) needed to auth the
  1256. # current event may be part of the batch and will not be in the DB yet
  1257. event_id_to_event = {e.event_id: e for e, _ in events_and_context}
  1258. batched_auth_events = {}
  1259. for event_id in event.auth_event_ids():
  1260. auth_event = event_id_to_event.get(event_id)
  1261. if auth_event:
  1262. batched_auth_events[event_id] = auth_event
  1263. await self._event_auth_handler.check_auth_rules_from_context(
  1264. event, batched_auth_events
  1265. )
  1266. except AuthError as err:
  1267. logger.warning("Denying new event %r because %s", event, err)
  1268. raise err
  1269. # Ensure that we can round trip before trying to persist in db
  1270. try:
  1271. dump = json_encoder.encode(event.content)
  1272. json_decoder.decode(dump)
  1273. except Exception:
  1274. logger.exception("Failed to encode content: %r", event.content)
  1275. raise
  1276. # We now persist the event (and update the cache in parallel, since we
  1277. # don't want to block on it).
  1278. #
  1279. # Note: mypy gets confused if we inline dl and check with twisted#11770.
  1280. # Some kind of bug in mypy's deduction?
  1281. deferreds = (
  1282. run_in_background(
  1283. self._persist_events,
  1284. requester=requester,
  1285. events_and_context=events_and_context,
  1286. ratelimit=ratelimit,
  1287. extra_users=extra_users,
  1288. ),
  1289. run_in_background(
  1290. self.cache_joined_hosts_for_events, events_and_context
  1291. ).addErrback(log_failure, "cache_joined_hosts_for_event failed"),
  1292. )
  1293. result, _ = await make_deferred_yieldable(
  1294. gather_results(deferreds, consumeErrors=True)
  1295. ).addErrback(unwrapFirstError)
  1296. return result
  1297. async def _persist_events(
  1298. self,
  1299. requester: Requester,
  1300. events_and_context: List[Tuple[EventBase, EventContext]],
  1301. ratelimit: bool = True,
  1302. extra_users: Optional[List[UserID]] = None,
  1303. ) -> EventBase:
  1304. """Actually persists new events. Should only be called by
  1305. `handle_new_client_event`, and see its docstring for documentation of
  1306. the arguments. Please note that if batch persisting events, an error in
  1307. handling any one of these events will result in all of the events being dropped.
  1308. PartialStateConflictError: if attempting to persist a partial state event in
  1309. a room that has been un-partial stated.
  1310. """
  1311. await self._bulk_push_rule_evaluator.action_for_events_by_user(
  1312. events_and_context
  1313. )
  1314. try:
  1315. # If we're a worker we need to hit out to the master.
  1316. first_event, _ = events_and_context[0]
  1317. writer_instance = self._events_shard_config.get_instance(
  1318. first_event.room_id
  1319. )
  1320. if writer_instance != self._instance_name:
  1321. # Ratelimit before sending to the other event persister, to
  1322. # ensure that we correctly have ratelimits on both the event
  1323. # creators and event persisters.
  1324. if ratelimit:
  1325. for event, _ in events_and_context:
  1326. is_admin_redaction = await self.is_admin_redaction(
  1327. event.type, event.sender, event.redacts
  1328. )
  1329. await self.request_ratelimiter.ratelimit(
  1330. requester, is_admin_redaction=is_admin_redaction
  1331. )
  1332. try:
  1333. result = await self.send_events(
  1334. instance_name=writer_instance,
  1335. events_and_context=events_and_context,
  1336. store=self.store,
  1337. requester=requester,
  1338. ratelimit=ratelimit,
  1339. extra_users=extra_users,
  1340. )
  1341. except SynapseError as e:
  1342. if e.code == HTTPStatus.CONFLICT:
  1343. raise PartialStateConflictError()
  1344. raise
  1345. stream_id = result["stream_id"]
  1346. event_id = result["event_id"]
  1347. # If we batch persisted events we return the last persisted event, otherwise
  1348. # we return the one event that was persisted
  1349. event, _ = events_and_context[-1]
  1350. if event_id != event.event_id:
  1351. # If we get a different event back then it means that its
  1352. # been de-duplicated, so we replace the given event with the
  1353. # one already persisted.
  1354. event = await self.store.get_event(event_id)
  1355. else:
  1356. # If we newly persisted the event then we need to update its
  1357. # stream_ordering entry manually (as it was persisted on
  1358. # another worker).
  1359. event.internal_metadata.stream_ordering = stream_id
  1360. return event
  1361. event = await self.persist_and_notify_client_events(
  1362. requester,
  1363. events_and_context,
  1364. ratelimit=ratelimit,
  1365. extra_users=extra_users,
  1366. )
  1367. return event
  1368. except Exception:
  1369. for event, _ in events_and_context:
  1370. # Ensure that we actually remove the entries in the push actions
  1371. # staging area, if we calculated them.
  1372. await self.store.remove_push_actions_from_staging(event.event_id)
  1373. raise
  1374. async def cache_joined_hosts_for_events(
  1375. self, events_and_context: List[Tuple[EventBase, EventContext]]
  1376. ) -> None:
  1377. """Precalculate the joined hosts at each of the given events, when using Redis, so that
  1378. external federation senders don't have to recalculate it themselves.
  1379. """
  1380. if not self._external_cache.is_enabled():
  1381. return
  1382. # If external cache is enabled we should always have this.
  1383. assert self._external_cache_joined_hosts_updates is not None
  1384. for event, event_context in events_and_context:
  1385. if event_context.partial_state:
  1386. # To populate the cache for a partial-state event, we either have to
  1387. # block until full state, which the code below does, or change the
  1388. # meaning of cache values to be the list of hosts to which we plan to
  1389. # send events and calculate that instead.
  1390. #
  1391. # The federation senders don't use the external cache when sending
  1392. # events in partial-state rooms anyway, so let's not bother populating
  1393. # the cache.
  1394. continue
  1395. # We actually store two mappings, event ID -> prev state group,
  1396. # state group -> joined hosts, which is much more space efficient
  1397. # than event ID -> joined hosts.
  1398. #
  1399. # Note: We have to cache event ID -> prev state group, as we don't
  1400. # store that in the DB.
  1401. #
  1402. # Note: We set the state group -> joined hosts cache if it hasn't been
  1403. # set for a while, so that the expiry time is reset.
  1404. state_entry = await self.state.resolve_state_groups_for_events(
  1405. event.room_id, event_ids=event.prev_event_ids()
  1406. )
  1407. if state_entry.state_group:
  1408. await self._external_cache.set(
  1409. "event_to_prev_state_group",
  1410. event.event_id,
  1411. state_entry.state_group,
  1412. expiry_ms=60 * 60 * 1000,
  1413. )
  1414. if state_entry.state_group in self._external_cache_joined_hosts_updates:
  1415. return
  1416. with opentracing.start_active_span("get_joined_hosts"):
  1417. joined_hosts = (
  1418. await self._storage_controllers.state.get_joined_hosts(
  1419. event.room_id, state_entry
  1420. )
  1421. )
  1422. # Note that the expiry times must be larger than the expiry time in
  1423. # _external_cache_joined_hosts_updates.
  1424. await self._external_cache.set(
  1425. "get_joined_hosts",
  1426. str(state_entry.state_group),
  1427. list(joined_hosts),
  1428. expiry_ms=60 * 60 * 1000,
  1429. )
  1430. self._external_cache_joined_hosts_updates[
  1431. state_entry.state_group
  1432. ] = None
  1433. async def _validate_canonical_alias(
  1434. self,
  1435. directory_handler: DirectoryHandler,
  1436. room_alias_str: str,
  1437. expected_room_id: str,
  1438. ) -> None:
  1439. """
  1440. Ensure that the given room alias points to the expected room ID.
  1441. Args:
  1442. directory_handler: The directory handler object.
  1443. room_alias_str: The room alias to check.
  1444. expected_room_id: The room ID that the alias should point to.
  1445. """
  1446. room_alias = RoomAlias.from_string(room_alias_str)
  1447. try:
  1448. mapping = await directory_handler.get_association(room_alias)
  1449. except SynapseError as e:
  1450. # Turn M_NOT_FOUND errors into M_BAD_ALIAS errors.
  1451. if e.errcode == Codes.NOT_FOUND:
  1452. raise SynapseError(
  1453. 400,
  1454. "Room alias %s does not point to the room" % (room_alias_str,),
  1455. Codes.BAD_ALIAS,
  1456. )
  1457. raise
  1458. if mapping["room_id"] != expected_room_id:
  1459. raise SynapseError(
  1460. 400,
  1461. "Room alias %s does not point to the room" % (room_alias_str,),
  1462. Codes.BAD_ALIAS,
  1463. )
  1464. async def persist_and_notify_client_events(
  1465. self,
  1466. requester: Requester,
  1467. events_and_context: List[Tuple[EventBase, EventContext]],
  1468. ratelimit: bool = True,
  1469. extra_users: Optional[List[UserID]] = None,
  1470. ) -> EventBase:
  1471. """Called when we have fully built the events, have already
  1472. calculated the push actions for the events, and checked auth.
  1473. This should only be run on the instance in charge of persisting events.
  1474. Please note that if batch persisting events, an error in
  1475. handling any one of these events will result in all of the events being dropped.
  1476. Returns:
  1477. The persisted event, if one event is passed in, or the last event in the
  1478. list in the case of batch persisting. If only one event was persisted, the
  1479. returned event may be different than the given event if it was de-duplicated
  1480. (e.g. because we had already persisted an event with the same transaction ID.)
  1481. Raises:
  1482. PartialStateConflictError: if attempting to persist a partial state event in
  1483. a room that has been un-partial stated.
  1484. """
  1485. extra_users = extra_users or []
  1486. for event, context in events_and_context:
  1487. assert self._events_shard_config.should_handle(
  1488. self._instance_name, event.room_id
  1489. )
  1490. if ratelimit:
  1491. # We check if this is a room admin redacting an event so that we
  1492. # can apply different ratelimiting. We do this by simply checking
  1493. # it's not a self-redaction (to avoid having to look up whether the
  1494. # user is actually admin or not).
  1495. is_admin_redaction = await self.is_admin_redaction(
  1496. event.type, event.sender, event.redacts
  1497. )
  1498. await self.request_ratelimiter.ratelimit(
  1499. requester, is_admin_redaction=is_admin_redaction
  1500. )
  1501. # run checks/actions on event based on type
  1502. if event.type == EventTypes.Member and event.membership == Membership.JOIN:
  1503. (
  1504. current_membership,
  1505. _,
  1506. ) = await self.store.get_local_current_membership_for_user_in_room(
  1507. event.state_key, event.room_id
  1508. )
  1509. if current_membership != Membership.JOIN:
  1510. self._notifier.notify_user_joined_room(
  1511. event.event_id, event.room_id
  1512. )
  1513. if event.type == EventTypes.ServerACL:
  1514. self._storage_controllers.state.get_server_acl_for_room.invalidate(
  1515. (event.room_id,)
  1516. )
  1517. await self._maybe_kick_guest_users(event, context)
  1518. if event.type == EventTypes.CanonicalAlias:
  1519. # Validate a newly added alias or newly added alt_aliases.
  1520. original_alias = None
  1521. original_alt_aliases: object = []
  1522. original_event_id = event.unsigned.get("replaces_state")
  1523. if original_event_id:
  1524. original_alias_event = await self.store.get_event(original_event_id)
  1525. if original_alias_event:
  1526. original_alias = original_alias_event.content.get("alias", None)
  1527. original_alt_aliases = original_alias_event.content.get(
  1528. "alt_aliases", []
  1529. )
  1530. # Check the alias is currently valid (if it has changed).
  1531. room_alias_str = event.content.get("alias", None)
  1532. directory_handler = self.hs.get_directory_handler()
  1533. if room_alias_str and room_alias_str != original_alias:
  1534. await self._validate_canonical_alias(
  1535. directory_handler, room_alias_str, event.room_id
  1536. )
  1537. # Check that alt_aliases is the proper form.
  1538. alt_aliases = event.content.get("alt_aliases", [])
  1539. if not isinstance(alt_aliases, (list, tuple)):
  1540. raise SynapseError(
  1541. 400,
  1542. "The alt_aliases property must be a list.",
  1543. Codes.INVALID_PARAM,
  1544. )
  1545. # If the old version of alt_aliases is of an unknown form,
  1546. # completely replace it.
  1547. if not isinstance(original_alt_aliases, (list, tuple)):
  1548. # TODO: check that the original_alt_aliases' entries are all strings
  1549. original_alt_aliases = []
  1550. # Check that each alias is currently valid.
  1551. new_alt_aliases = set(alt_aliases) - set(original_alt_aliases)
  1552. if new_alt_aliases:
  1553. for alias_str in new_alt_aliases:
  1554. await self._validate_canonical_alias(
  1555. directory_handler, alias_str, event.room_id
  1556. )
  1557. federation_handler = self.hs.get_federation_handler()
  1558. if event.type == EventTypes.Member:
  1559. if event.content["membership"] == Membership.INVITE:
  1560. maybe_upsert_event_field(
  1561. event,
  1562. event.unsigned,
  1563. "invite_room_state",
  1564. await self.store.get_stripped_room_state_from_event_context(
  1565. context,
  1566. self.room_prejoin_state_types,
  1567. membership_user_id=event.sender,
  1568. ),
  1569. )
  1570. invitee = UserID.from_string(event.state_key)
  1571. if not self.hs.is_mine(invitee):
  1572. # TODO: Can we add signature from remote server in a nicer
  1573. # way? If we have been invited by a remote server, we need
  1574. # to get them to sign the event.
  1575. returned_invite = await federation_handler.send_invite(
  1576. invitee.domain, event
  1577. )
  1578. event.unsigned.pop("room_state", None)
  1579. # TODO: Make sure the signatures actually are correct.
  1580. event.signatures.update(returned_invite.signatures)
  1581. if event.content["membership"] == Membership.KNOCK:
  1582. maybe_upsert_event_field(
  1583. event,
  1584. event.unsigned,
  1585. "knock_room_state",
  1586. await self.store.get_stripped_room_state_from_event_context(
  1587. context,
  1588. self.room_prejoin_state_types,
  1589. ),
  1590. )
  1591. if event.type == EventTypes.Redaction:
  1592. assert event.redacts is not None
  1593. original_event = await self.store.get_event(
  1594. event.redacts,
  1595. redact_behaviour=EventRedactBehaviour.as_is,
  1596. get_prev_content=False,
  1597. allow_rejected=False,
  1598. allow_none=True,
  1599. )
  1600. room_version = await self.store.get_room_version_id(event.room_id)
  1601. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1602. # we can make some additional checks now if we have the original event.
  1603. if original_event:
  1604. if original_event.type == EventTypes.Create:
  1605. raise AuthError(403, "Redacting create events is not permitted")
  1606. if original_event.room_id != event.room_id:
  1607. raise SynapseError(
  1608. 400, "Cannot redact event from a different room"
  1609. )
  1610. if original_event.type == EventTypes.ServerACL:
  1611. raise AuthError(
  1612. 403, "Redacting server ACL events is not permitted"
  1613. )
  1614. event_types = event_auth.auth_types_for_event(event.room_version, event)
  1615. prev_state_ids = await context.get_prev_state_ids(
  1616. StateFilter.from_types(event_types)
  1617. )
  1618. auth_events_ids = self._event_auth_handler.compute_auth_events(
  1619. event, prev_state_ids, for_verification=True
  1620. )
  1621. auth_events_map = await self.store.get_events(auth_events_ids)
  1622. auth_events = {
  1623. (e.type, e.state_key): e for e in auth_events_map.values()
  1624. }
  1625. if event_auth.check_redaction(
  1626. room_version_obj, event, auth_events=auth_events
  1627. ):
  1628. # this user doesn't have 'redact' rights, so we need to do some more
  1629. # checks on the original event. Let's start by checking the original
  1630. # event exists.
  1631. if not original_event:
  1632. raise NotFoundError(
  1633. "Could not find event %s" % (event.redacts,)
  1634. )
  1635. if event.user_id != original_event.user_id:
  1636. raise AuthError(
  1637. 403, "You don't have permission to redact events"
  1638. )
  1639. # all the checks are done.
  1640. event.internal_metadata.recheck_redaction = False
  1641. if event.type == EventTypes.Create:
  1642. prev_state_ids = await context.get_prev_state_ids()
  1643. if prev_state_ids:
  1644. raise AuthError(403, "Changing the room create event is forbidden")
  1645. assert self._storage_controllers.persistence is not None
  1646. (
  1647. persisted_events,
  1648. max_stream_token,
  1649. ) = await self._storage_controllers.persistence.persist_events(
  1650. events_and_context,
  1651. )
  1652. events_and_pos = []
  1653. for event in persisted_events:
  1654. if self._ephemeral_events_enabled:
  1655. # If there's an expiry timestamp on the event, schedule its expiry.
  1656. self._message_handler.maybe_schedule_expiry(event)
  1657. stream_ordering = event.internal_metadata.stream_ordering
  1658. assert stream_ordering is not None
  1659. pos = PersistedEventPosition(self._instance_name, stream_ordering)
  1660. events_and_pos.append((event, pos))
  1661. if event.type == EventTypes.Message:
  1662. # We don't want to block sending messages on any presence code. This
  1663. # matters as sometimes presence code can take a while.
  1664. run_as_background_process(
  1665. "bump_presence_active_time",
  1666. self._bump_active_time,
  1667. requester.user,
  1668. requester.device_id,
  1669. )
  1670. async def _notify() -> None:
  1671. try:
  1672. await self.notifier.on_new_room_events(
  1673. events_and_pos, max_stream_token, extra_users=extra_users
  1674. )
  1675. except Exception:
  1676. logger.exception("Error notifying about new room events")
  1677. run_in_background(_notify)
  1678. return persisted_events[-1]
  1679. async def is_admin_redaction(
  1680. self, event_type: str, sender: str, redacts: Optional[str]
  1681. ) -> bool:
  1682. """Return whether the event is a redaction made by an admin, and thus
  1683. should use a different ratelimiter.
  1684. """
  1685. if event_type != EventTypes.Redaction:
  1686. return False
  1687. assert redacts is not None
  1688. original_event = await self.store.get_event(
  1689. redacts,
  1690. redact_behaviour=EventRedactBehaviour.as_is,
  1691. get_prev_content=False,
  1692. allow_rejected=False,
  1693. allow_none=True,
  1694. )
  1695. return bool(original_event and sender != original_event.sender)
  1696. async def _maybe_kick_guest_users(
  1697. self, event: EventBase, context: EventContext
  1698. ) -> None:
  1699. if event.type != EventTypes.GuestAccess:
  1700. return
  1701. guest_access = event.content.get(EventContentFields.GUEST_ACCESS)
  1702. if guest_access == GuestAccess.CAN_JOIN:
  1703. return
  1704. current_state_ids = await context.get_current_state_ids()
  1705. # since this is a client-generated event, it cannot be an outlier and we must
  1706. # therefore have the state ids.
  1707. assert current_state_ids is not None
  1708. current_state_dict = await self.store.get_events(
  1709. list(current_state_ids.values())
  1710. )
  1711. current_state = list(current_state_dict.values())
  1712. logger.info("maybe_kick_guest_users %r", current_state)
  1713. await self.hs.get_room_member_handler().kick_guest_users(current_state)
  1714. async def _bump_active_time(self, user: UserID, device_id: Optional[str]) -> None:
  1715. try:
  1716. presence = self.hs.get_presence_handler()
  1717. await presence.bump_presence_active_time(user, device_id)
  1718. except Exception:
  1719. logger.exception("Error bumping presence active time")
  1720. async def _send_dummy_events_to_fill_extremities(self) -> None:
  1721. """Background task to send dummy events into rooms that have a large
  1722. number of extremities
  1723. """
  1724. self._expire_rooms_to_exclude_from_dummy_event_insertion()
  1725. room_ids = await self.store.get_rooms_with_many_extremities(
  1726. min_count=self._dummy_events_threshold,
  1727. limit=5,
  1728. room_id_filter=self._rooms_to_exclude_from_dummy_event_insertion.keys(),
  1729. )
  1730. for room_id in room_ids:
  1731. async with self._worker_lock_handler.acquire_read_write_lock(
  1732. NEW_EVENT_DURING_PURGE_LOCK_NAME, room_id, write=False
  1733. ):
  1734. dummy_event_sent = await self._send_dummy_event_for_room(room_id)
  1735. if not dummy_event_sent:
  1736. # Did not find a valid user in the room, so remove from future attempts
  1737. # Exclusion is time limited, so the room will be rechecked in the future
  1738. # dependent on _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY
  1739. logger.info(
  1740. "Failed to send dummy event into room %s. Will exclude it from "
  1741. "future attempts until cache expires" % (room_id,)
  1742. )
  1743. now = self.clock.time_msec()
  1744. self._rooms_to_exclude_from_dummy_event_insertion[room_id] = now
  1745. async def _send_dummy_event_for_room(self, room_id: str) -> bool:
  1746. """Attempt to send a dummy event for the given room.
  1747. Args:
  1748. room_id: room to try to send an event from
  1749. Returns:
  1750. True if a dummy event was successfully sent. False if no user was able
  1751. to send an event.
  1752. """
  1753. # For each room we need to find a joined member we can use to send
  1754. # the dummy event with.
  1755. members = await self.store.get_local_users_in_room(room_id)
  1756. for user_id in members:
  1757. requester = create_requester(user_id, authenticated_entity=self.server_name)
  1758. try:
  1759. # Try several times, it could fail with PartialStateConflictError
  1760. # in handle_new_client_event, cf comment in except block.
  1761. max_retries = 5
  1762. for i in range(max_retries):
  1763. try:
  1764. event, unpersisted_context = await self.create_event(
  1765. requester,
  1766. {
  1767. "type": EventTypes.Dummy,
  1768. "content": {},
  1769. "room_id": room_id,
  1770. "sender": user_id,
  1771. },
  1772. )
  1773. context = await unpersisted_context.persist(event)
  1774. event.internal_metadata.proactively_send = False
  1775. # Since this is a dummy-event it is OK if it is sent by a
  1776. # shadow-banned user.
  1777. await self.handle_new_client_event(
  1778. requester,
  1779. events_and_context=[(event, context)],
  1780. ratelimit=False,
  1781. ignore_shadow_ban=True,
  1782. )
  1783. break
  1784. except PartialStateConflictError as e:
  1785. # Persisting couldn't happen because the room got un-partial stated
  1786. # in the meantime and context needs to be recomputed, so let's do so.
  1787. if i == max_retries - 1:
  1788. raise e
  1789. return True
  1790. except AuthError:
  1791. logger.info(
  1792. "Failed to send dummy event into room %s for user %s due to "
  1793. "lack of power. Will try another user" % (room_id, user_id)
  1794. )
  1795. return False
  1796. def _expire_rooms_to_exclude_from_dummy_event_insertion(self) -> None:
  1797. expire_before = self.clock.time_msec() - _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY
  1798. to_expire = set()
  1799. for room_id, time in self._rooms_to_exclude_from_dummy_event_insertion.items():
  1800. if time < expire_before:
  1801. to_expire.add(room_id)
  1802. for room_id in to_expire:
  1803. logger.debug(
  1804. "Expiring room id %s from dummy event insertion exclusion cache",
  1805. room_id,
  1806. )
  1807. del self._rooms_to_exclude_from_dummy_event_insertion[room_id]
  1808. async def _rebuild_event_after_third_party_rules(
  1809. self, third_party_result: dict, original_event: EventBase
  1810. ) -> Tuple[EventBase, UnpersistedEventContextBase]:
  1811. # the third_party_event_rules want to replace the event.
  1812. # we do some basic checks, and then return the replacement event.
  1813. # Construct a new EventBuilder and validate it, which helps with the
  1814. # rest of these checks.
  1815. try:
  1816. builder = self.event_builder_factory.for_room_version(
  1817. original_event.room_version, third_party_result
  1818. )
  1819. self.validator.validate_builder(builder)
  1820. except SynapseError as e:
  1821. raise Exception(
  1822. "Third party rules module created an invalid event: " + e.msg,
  1823. )
  1824. immutable_fields = [
  1825. # changing the room is going to break things: we've already checked that the
  1826. # room exists, and are holding a concurrency limiter token for that room.
  1827. # Also, we might need to use a different room version.
  1828. "room_id",
  1829. # changing the type or state key might work, but we'd need to check that the
  1830. # calling functions aren't making assumptions about them.
  1831. "type",
  1832. "state_key",
  1833. ]
  1834. for k in immutable_fields:
  1835. if getattr(builder, k, None) != original_event.get(k):
  1836. raise Exception(
  1837. "Third party rules module created an invalid event: "
  1838. "cannot change field " + k
  1839. )
  1840. # check that the new sender belongs to this HS
  1841. if not self.hs.is_mine_id(builder.sender):
  1842. raise Exception(
  1843. "Third party rules module created an invalid event: "
  1844. "invalid sender " + builder.sender
  1845. )
  1846. # copy over the original internal metadata
  1847. for k, v in original_event.internal_metadata.get_dict().items():
  1848. setattr(builder.internal_metadata, k, v)
  1849. # modules can send new state events, so we re-calculate the auth events just in
  1850. # case.
  1851. prev_event_ids = await self.store.get_prev_events_for_room(builder.room_id)
  1852. event = await builder.build(
  1853. prev_event_ids=prev_event_ids,
  1854. auth_event_ids=None,
  1855. )
  1856. # we rebuild the event context, to be on the safe side. If nothing else,
  1857. # delta_ids might need an update.
  1858. context = await self.state.calculate_context_info(event)
  1859. return event, context