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

1936 lines
75 KiB

  1. # Copyright 2016-2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains functions for performing actions on rooms."""
  15. import itertools
  16. import logging
  17. import math
  18. import random
  19. import string
  20. from collections import OrderedDict
  21. from http import HTTPStatus
  22. from typing import TYPE_CHECKING, Any, Awaitable, Dict, List, Optional, Tuple
  23. import attr
  24. from typing_extensions import TypedDict
  25. import synapse.events.snapshot
  26. from synapse.api.constants import (
  27. Direction,
  28. EventContentFields,
  29. EventTypes,
  30. GuestAccess,
  31. HistoryVisibility,
  32. JoinRules,
  33. Membership,
  34. RoomCreationPreset,
  35. RoomEncryptionAlgorithms,
  36. RoomTypes,
  37. )
  38. from synapse.api.errors import (
  39. AuthError,
  40. Codes,
  41. LimitExceededError,
  42. NotFoundError,
  43. PartialStateConflictError,
  44. StoreError,
  45. SynapseError,
  46. )
  47. from synapse.api.filtering import Filter
  48. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
  49. from synapse.event_auth import validate_event_for_room_version
  50. from synapse.events import EventBase
  51. from synapse.events.utils import copy_and_fixup_power_levels_contents
  52. from synapse.handlers.relations import BundledAggregations
  53. from synapse.module_api import NOT_SPAM
  54. from synapse.rest.admin._base import assert_user_is_admin
  55. from synapse.streams import EventSource
  56. from synapse.types import (
  57. JsonDict,
  58. MutableStateMap,
  59. Requester,
  60. RoomAlias,
  61. RoomID,
  62. RoomStreamToken,
  63. StateMap,
  64. StrCollection,
  65. StreamKeyType,
  66. StreamToken,
  67. UserID,
  68. create_requester,
  69. )
  70. from synapse.types.state import StateFilter
  71. from synapse.util import stringutils
  72. from synapse.util.caches.response_cache import ResponseCache
  73. from synapse.util.stringutils import parse_and_validate_server_name
  74. from synapse.visibility import filter_events_for_client
  75. if TYPE_CHECKING:
  76. from synapse.server import HomeServer
  77. logger = logging.getLogger(__name__)
  78. id_server_scheme = "https://"
  79. FIVE_MINUTES_IN_MS = 5 * 60 * 1000
  80. @attr.s(slots=True, frozen=True, auto_attribs=True)
  81. class EventContext:
  82. events_before: List[EventBase]
  83. event: EventBase
  84. events_after: List[EventBase]
  85. state: List[EventBase]
  86. aggregations: Dict[str, BundledAggregations]
  87. start: str
  88. end: str
  89. class RoomCreationHandler:
  90. def __init__(self, hs: "HomeServer"):
  91. self.store = hs.get_datastores().main
  92. self._storage_controllers = hs.get_storage_controllers()
  93. self.auth = hs.get_auth()
  94. self.auth_blocking = hs.get_auth_blocking()
  95. self.clock = hs.get_clock()
  96. self.hs = hs
  97. self.spam_checker = hs.get_spam_checker()
  98. self.event_creation_handler = hs.get_event_creation_handler()
  99. self.room_member_handler = hs.get_room_member_handler()
  100. self._event_auth_handler = hs.get_event_auth_handler()
  101. self.config = hs.config
  102. self.request_ratelimiter = hs.get_request_ratelimiter()
  103. # Room state based off defined presets
  104. self._presets_dict: Dict[str, Dict[str, Any]] = {
  105. RoomCreationPreset.PRIVATE_CHAT: {
  106. "join_rules": JoinRules.INVITE,
  107. "history_visibility": HistoryVisibility.SHARED,
  108. "original_invitees_have_ops": False,
  109. "guest_can_join": True,
  110. "power_level_content_override": {"invite": 0},
  111. },
  112. RoomCreationPreset.TRUSTED_PRIVATE_CHAT: {
  113. "join_rules": JoinRules.INVITE,
  114. "history_visibility": HistoryVisibility.SHARED,
  115. "original_invitees_have_ops": True,
  116. "guest_can_join": True,
  117. "power_level_content_override": {"invite": 0},
  118. },
  119. RoomCreationPreset.PUBLIC_CHAT: {
  120. "join_rules": JoinRules.PUBLIC,
  121. "history_visibility": HistoryVisibility.SHARED,
  122. "original_invitees_have_ops": False,
  123. "guest_can_join": False,
  124. "power_level_content_override": {},
  125. },
  126. }
  127. # Modify presets to selectively enable encryption by default per homeserver config
  128. for preset_name, preset_config in self._presets_dict.items():
  129. encrypted = (
  130. preset_name
  131. in self.config.room.encryption_enabled_by_default_for_room_presets
  132. )
  133. preset_config["encrypted"] = encrypted
  134. self._default_power_level_content_override = (
  135. self.config.room.default_power_level_content_override
  136. )
  137. self._replication = hs.get_replication_data_handler()
  138. # If a user tries to update the same room multiple times in quick
  139. # succession, only process the first attempt and return its result to
  140. # subsequent requests
  141. self._upgrade_response_cache: ResponseCache[Tuple[str, str]] = ResponseCache(
  142. hs.get_clock(), "room_upgrade", timeout_ms=FIVE_MINUTES_IN_MS
  143. )
  144. self._server_notices_mxid = hs.config.servernotices.server_notices_mxid
  145. self.third_party_event_rules = hs.get_third_party_event_rules()
  146. async def upgrade_room(
  147. self, requester: Requester, old_room_id: str, new_version: RoomVersion
  148. ) -> str:
  149. """Replace a room with a new room with a different version
  150. Args:
  151. requester: the user requesting the upgrade
  152. old_room_id: the id of the room to be replaced
  153. new_version: the new room version to use
  154. Returns:
  155. the new room id
  156. Raises:
  157. ShadowBanError if the requester is shadow-banned.
  158. """
  159. await self.request_ratelimiter.ratelimit(requester)
  160. user_id = requester.user.to_string()
  161. # Check if this room is already being upgraded by another person
  162. for key in self._upgrade_response_cache.keys():
  163. if key[0] == old_room_id and key[1] != user_id:
  164. # Two different people are trying to upgrade the same room.
  165. # Send the second an error.
  166. #
  167. # Note that this of course only gets caught if both users are
  168. # on the same homeserver.
  169. raise SynapseError(
  170. 400, "An upgrade for this room is currently in progress"
  171. )
  172. # Check whether the room exists and 404 if it doesn't.
  173. # We could go straight for the auth check, but that will raise a 403 instead.
  174. old_room = await self.store.get_room(old_room_id)
  175. if old_room is None:
  176. raise NotFoundError("Unknown room id %s" % (old_room_id,))
  177. new_room_id = self._generate_room_id()
  178. # Try several times, it could fail with PartialStateConflictError
  179. # in _upgrade_room, cf comment in except block.
  180. max_retries = 5
  181. for i in range(max_retries):
  182. try:
  183. # Check whether the user has the power level to carry out the upgrade.
  184. # `check_auth_rules_from_context` will check that they are in the room and have
  185. # the required power level to send the tombstone event.
  186. (
  187. tombstone_event,
  188. tombstone_context,
  189. ) = await self.event_creation_handler.create_event(
  190. requester,
  191. {
  192. "type": EventTypes.Tombstone,
  193. "state_key": "",
  194. "room_id": old_room_id,
  195. "sender": user_id,
  196. "content": {
  197. "body": "This room has been replaced",
  198. "replacement_room": new_room_id,
  199. },
  200. },
  201. )
  202. validate_event_for_room_version(tombstone_event)
  203. await self._event_auth_handler.check_auth_rules_from_context(
  204. tombstone_event
  205. )
  206. # Upgrade the room
  207. #
  208. # If this user has sent multiple upgrade requests for the same room
  209. # and one of them is not complete yet, cache the response and
  210. # return it to all subsequent requests
  211. ret = await self._upgrade_response_cache.wrap(
  212. (old_room_id, user_id),
  213. self._upgrade_room,
  214. requester,
  215. old_room_id,
  216. old_room, # args for _upgrade_room
  217. new_room_id,
  218. new_version,
  219. tombstone_event,
  220. tombstone_context,
  221. )
  222. return ret
  223. except PartialStateConflictError as e:
  224. # Clean up the cache so we can retry properly
  225. self._upgrade_response_cache.unset((old_room_id, user_id))
  226. # Persisting couldn't happen because the room got un-partial stated
  227. # in the meantime and context needs to be recomputed, so let's do so.
  228. if i == max_retries - 1:
  229. raise e
  230. pass
  231. # This is to satisfy mypy and should never happen
  232. raise PartialStateConflictError()
  233. async def _upgrade_room(
  234. self,
  235. requester: Requester,
  236. old_room_id: str,
  237. old_room: Dict[str, Any],
  238. new_room_id: str,
  239. new_version: RoomVersion,
  240. tombstone_event: EventBase,
  241. tombstone_context: synapse.events.snapshot.EventContext,
  242. ) -> str:
  243. """
  244. Args:
  245. requester: the user requesting the upgrade
  246. old_room_id: the id of the room to be replaced
  247. old_room: a dict containing room information for the room to be replaced,
  248. as returned by `RoomWorkerStore.get_room`.
  249. new_room_id: the id of the replacement room
  250. new_version: the version to upgrade the room to
  251. tombstone_event: the tombstone event to send to the old room
  252. tombstone_context: the context for the tombstone event
  253. Raises:
  254. ShadowBanError if the requester is shadow-banned.
  255. """
  256. user_id = requester.user.to_string()
  257. assert self.hs.is_mine_id(user_id), "User must be our own: %s" % (user_id,)
  258. logger.info("Creating new room %s to replace %s", new_room_id, old_room_id)
  259. # create the new room. may raise a `StoreError` in the exceedingly unlikely
  260. # event of a room ID collision.
  261. await self.store.store_room(
  262. room_id=new_room_id,
  263. room_creator_user_id=user_id,
  264. is_public=old_room["is_public"],
  265. room_version=new_version,
  266. )
  267. await self.clone_existing_room(
  268. requester,
  269. old_room_id=old_room_id,
  270. new_room_id=new_room_id,
  271. new_room_version=new_version,
  272. tombstone_event_id=tombstone_event.event_id,
  273. )
  274. # now send the tombstone
  275. await self.event_creation_handler.handle_new_client_event(
  276. requester=requester,
  277. events_and_context=[(tombstone_event, tombstone_context)],
  278. )
  279. state_filter = StateFilter.from_types(
  280. [(EventTypes.CanonicalAlias, ""), (EventTypes.PowerLevels, "")]
  281. )
  282. old_room_state = await tombstone_context.get_current_state_ids(state_filter)
  283. # We know the tombstone event isn't an outlier so it has current state.
  284. assert old_room_state is not None
  285. # update any aliases
  286. await self._move_aliases_to_new_room(
  287. requester, old_room_id, new_room_id, old_room_state
  288. )
  289. # Copy over user push rules, tags and migrate room directory state
  290. await self.room_member_handler.transfer_room_state_on_room_upgrade(
  291. old_room_id, new_room_id
  292. )
  293. # finally, shut down the PLs in the old room, and update them in the new
  294. # room.
  295. await self._update_upgraded_room_pls(
  296. requester,
  297. old_room_id,
  298. new_room_id,
  299. old_room_state,
  300. )
  301. return new_room_id
  302. async def _update_upgraded_room_pls(
  303. self,
  304. requester: Requester,
  305. old_room_id: str,
  306. new_room_id: str,
  307. old_room_state: StateMap[str],
  308. ) -> None:
  309. """Send updated power levels in both rooms after an upgrade
  310. Args:
  311. requester: the user requesting the upgrade
  312. old_room_id: the id of the room to be replaced
  313. new_room_id: the id of the replacement room
  314. old_room_state: the state map for the old room
  315. Raises:
  316. ShadowBanError if the requester is shadow-banned.
  317. """
  318. old_room_pl_event_id = old_room_state.get((EventTypes.PowerLevels, ""))
  319. if old_room_pl_event_id is None:
  320. logger.warning(
  321. "Not supported: upgrading a room with no PL event. Not setting PLs "
  322. "in old room."
  323. )
  324. return
  325. old_room_pl_state = await self.store.get_event(old_room_pl_event_id)
  326. # we try to stop regular users from speaking by setting the PL required
  327. # to send regular events and invites to 'Moderator' level. That's normally
  328. # 50, but if the default PL in a room is 50 or more, then we set the
  329. # required PL above that.
  330. pl_content = copy_and_fixup_power_levels_contents(old_room_pl_state.content)
  331. users_default: int = pl_content.get("users_default", 0) # type: ignore[assignment]
  332. restricted_level = max(users_default + 1, 50)
  333. updated = False
  334. for v in ("invite", "events_default"):
  335. current: int = pl_content.get(v, 0) # type: ignore[assignment]
  336. if current < restricted_level:
  337. logger.debug(
  338. "Setting level for %s in %s to %i (was %i)",
  339. v,
  340. old_room_id,
  341. restricted_level,
  342. current,
  343. )
  344. pl_content[v] = restricted_level
  345. updated = True
  346. else:
  347. logger.debug("Not setting level for %s (already %i)", v, current)
  348. if updated:
  349. try:
  350. await self.event_creation_handler.create_and_send_nonmember_event(
  351. requester,
  352. {
  353. "type": EventTypes.PowerLevels,
  354. "state_key": "",
  355. "room_id": old_room_id,
  356. "sender": requester.user.to_string(),
  357. "content": pl_content,
  358. },
  359. ratelimit=False,
  360. )
  361. except AuthError as e:
  362. logger.warning("Unable to update PLs in old room: %s", e)
  363. await self.event_creation_handler.create_and_send_nonmember_event(
  364. requester,
  365. {
  366. "type": EventTypes.PowerLevels,
  367. "state_key": "",
  368. "room_id": new_room_id,
  369. "sender": requester.user.to_string(),
  370. "content": copy_and_fixup_power_levels_contents(
  371. old_room_pl_state.content
  372. ),
  373. },
  374. ratelimit=False,
  375. )
  376. async def clone_existing_room(
  377. self,
  378. requester: Requester,
  379. old_room_id: str,
  380. new_room_id: str,
  381. new_room_version: RoomVersion,
  382. tombstone_event_id: str,
  383. ) -> None:
  384. """Populate a new room based on an old room
  385. Args:
  386. requester: the user requesting the upgrade
  387. old_room_id : the id of the room to be replaced
  388. new_room_id: the id to give the new room (should already have been
  389. created with _generate_room_id())
  390. new_room_version: the new room version to use
  391. tombstone_event_id: the ID of the tombstone event in the old room.
  392. """
  393. user_id = requester.user.to_string()
  394. spam_check = await self.spam_checker.user_may_create_room(user_id)
  395. if spam_check != NOT_SPAM:
  396. raise SynapseError(
  397. 403,
  398. "You are not permitted to create rooms",
  399. errcode=spam_check[0],
  400. additional_fields=spam_check[1],
  401. )
  402. creation_content: JsonDict = {
  403. "room_version": new_room_version.identifier,
  404. "predecessor": {"room_id": old_room_id, "event_id": tombstone_event_id},
  405. }
  406. # Check if old room was non-federatable
  407. # Get old room's create event
  408. old_room_create_event = await self.store.get_create_event_for_room(old_room_id)
  409. # Check if the create event specified a non-federatable room
  410. if not old_room_create_event.content.get(EventContentFields.FEDERATE, True):
  411. # If so, mark the new room as non-federatable as well
  412. creation_content[EventContentFields.FEDERATE] = False
  413. initial_state = {}
  414. # Replicate relevant room events
  415. types_to_copy: List[Tuple[str, Optional[str]]] = [
  416. (EventTypes.JoinRules, ""),
  417. (EventTypes.Name, ""),
  418. (EventTypes.Topic, ""),
  419. (EventTypes.RoomHistoryVisibility, ""),
  420. (EventTypes.GuestAccess, ""),
  421. (EventTypes.RoomAvatar, ""),
  422. (EventTypes.RoomEncryption, ""),
  423. (EventTypes.ServerACL, ""),
  424. (EventTypes.PowerLevels, ""),
  425. ]
  426. # Copy the room type as per MSC3818.
  427. room_type = old_room_create_event.content.get(EventContentFields.ROOM_TYPE)
  428. if room_type is not None:
  429. creation_content[EventContentFields.ROOM_TYPE] = room_type
  430. # If the old room was a space, copy over the rooms in the space.
  431. if room_type == RoomTypes.SPACE:
  432. types_to_copy.append((EventTypes.SpaceChild, None))
  433. old_room_state_ids = (
  434. await self._storage_controllers.state.get_current_state_ids(
  435. old_room_id, StateFilter.from_types(types_to_copy)
  436. )
  437. )
  438. # map from event_id to BaseEvent
  439. old_room_state_events = await self.store.get_events(old_room_state_ids.values())
  440. for k, old_event_id in old_room_state_ids.items():
  441. old_event = old_room_state_events.get(old_event_id)
  442. if old_event:
  443. # If the event is an space child event with empty content, it was
  444. # removed from the space and should be ignored.
  445. if k[0] == EventTypes.SpaceChild and not old_event.content:
  446. continue
  447. initial_state[k] = old_event.content
  448. # deep-copy the power-levels event before we start modifying it
  449. # note that if frozen_dicts are enabled, `power_levels` will be a frozen
  450. # dict so we can't just copy.deepcopy it.
  451. initial_state[
  452. (EventTypes.PowerLevels, "")
  453. ] = power_levels = copy_and_fixup_power_levels_contents(
  454. initial_state[(EventTypes.PowerLevels, "")]
  455. )
  456. # Resolve the minimum power level required to send any state event
  457. # We will give the upgrading user this power level temporarily (if necessary) such that
  458. # they are able to copy all of the state events over, then revert them back to their
  459. # original power level afterwards in _update_upgraded_room_pls
  460. # Copy over user power levels now as this will not be possible with >100PL users once
  461. # the room has been created
  462. # Calculate the minimum power level needed to clone the room
  463. event_power_levels = power_levels.get("events", {})
  464. if not isinstance(event_power_levels, dict):
  465. event_power_levels = {}
  466. state_default = power_levels.get("state_default", 50)
  467. try:
  468. state_default_int = int(state_default) # type: ignore[arg-type]
  469. except (TypeError, ValueError):
  470. state_default_int = 50
  471. ban = power_levels.get("ban", 50)
  472. try:
  473. ban = int(ban) # type: ignore[arg-type]
  474. except (TypeError, ValueError):
  475. ban = 50
  476. needed_power_level = max(
  477. state_default_int, ban, max(event_power_levels.values())
  478. )
  479. # Get the user's current power level, this matches the logic in get_user_power_level,
  480. # but without the entire state map.
  481. user_power_levels = power_levels.setdefault("users", {})
  482. if not isinstance(user_power_levels, dict):
  483. user_power_levels = {}
  484. users_default = power_levels.get("users_default", 0)
  485. current_power_level = user_power_levels.get(user_id, users_default)
  486. try:
  487. current_power_level_int = int(current_power_level) # type: ignore[arg-type]
  488. except (TypeError, ValueError):
  489. current_power_level_int = 0
  490. # Raise the requester's power level in the new room if necessary
  491. if current_power_level_int < needed_power_level:
  492. user_power_levels[user_id] = needed_power_level
  493. await self._send_events_for_new_room(
  494. requester,
  495. new_room_id,
  496. # we expect to override all the presets with initial_state, so this is
  497. # somewhat arbitrary.
  498. preset_config=RoomCreationPreset.PRIVATE_CHAT,
  499. invite_list=[],
  500. initial_state=initial_state,
  501. creation_content=creation_content,
  502. )
  503. # Transfer membership events
  504. old_room_member_state_ids = (
  505. await self._storage_controllers.state.get_current_state_ids(
  506. old_room_id, StateFilter.from_types([(EventTypes.Member, None)])
  507. )
  508. )
  509. # map from event_id to BaseEvent
  510. old_room_member_state_events = await self.store.get_events(
  511. old_room_member_state_ids.values()
  512. )
  513. for old_event in old_room_member_state_events.values():
  514. # Only transfer ban events
  515. if (
  516. "membership" in old_event.content
  517. and old_event.content["membership"] == "ban"
  518. ):
  519. await self.room_member_handler.update_membership(
  520. requester,
  521. UserID.from_string(old_event.state_key),
  522. new_room_id,
  523. "ban",
  524. ratelimit=False,
  525. content=old_event.content,
  526. )
  527. # XXX invites/joins
  528. # XXX 3pid invites
  529. async def _move_aliases_to_new_room(
  530. self,
  531. requester: Requester,
  532. old_room_id: str,
  533. new_room_id: str,
  534. old_room_state: StateMap[str],
  535. ) -> None:
  536. # check to see if we have a canonical alias.
  537. canonical_alias_event = None
  538. canonical_alias_event_id = old_room_state.get((EventTypes.CanonicalAlias, ""))
  539. if canonical_alias_event_id:
  540. canonical_alias_event = await self.store.get_event(canonical_alias_event_id)
  541. await self.store.update_aliases_for_room(old_room_id, new_room_id)
  542. if not canonical_alias_event:
  543. return
  544. # If there is a canonical alias we need to update the one in the old
  545. # room and set one in the new one.
  546. old_canonical_alias_content = dict(canonical_alias_event.content)
  547. new_canonical_alias_content = {}
  548. canonical = canonical_alias_event.content.get("alias")
  549. if canonical and self.hs.is_mine_id(canonical):
  550. new_canonical_alias_content["alias"] = canonical
  551. old_canonical_alias_content.pop("alias", None)
  552. # We convert to a list as it will be a Tuple.
  553. old_alt_aliases = list(old_canonical_alias_content.get("alt_aliases", []))
  554. if old_alt_aliases:
  555. old_canonical_alias_content["alt_aliases"] = old_alt_aliases
  556. new_alt_aliases = new_canonical_alias_content.setdefault("alt_aliases", [])
  557. for alias in canonical_alias_event.content.get("alt_aliases", []):
  558. try:
  559. if self.hs.is_mine_id(alias):
  560. new_alt_aliases.append(alias)
  561. old_alt_aliases.remove(alias)
  562. except Exception:
  563. logger.info(
  564. "Invalid alias %s in canonical alias event %s",
  565. alias,
  566. canonical_alias_event_id,
  567. )
  568. if not old_alt_aliases:
  569. old_canonical_alias_content.pop("alt_aliases")
  570. # If a canonical alias event existed for the old room, fire a canonical
  571. # alias event for the new room with a copy of the information.
  572. try:
  573. await self.event_creation_handler.create_and_send_nonmember_event(
  574. requester,
  575. {
  576. "type": EventTypes.CanonicalAlias,
  577. "state_key": "",
  578. "room_id": old_room_id,
  579. "sender": requester.user.to_string(),
  580. "content": old_canonical_alias_content,
  581. },
  582. ratelimit=False,
  583. )
  584. except SynapseError as e:
  585. # again I'm not really expecting this to fail, but if it does, I'd rather
  586. # we returned the new room to the client at this point.
  587. logger.error("Unable to send updated alias events in old room: %s", e)
  588. try:
  589. await self.event_creation_handler.create_and_send_nonmember_event(
  590. requester,
  591. {
  592. "type": EventTypes.CanonicalAlias,
  593. "state_key": "",
  594. "room_id": new_room_id,
  595. "sender": requester.user.to_string(),
  596. "content": new_canonical_alias_content,
  597. },
  598. ratelimit=False,
  599. )
  600. except SynapseError as e:
  601. # again I'm not really expecting this to fail, but if it does, I'd rather
  602. # we returned the new room to the client at this point.
  603. logger.error("Unable to send updated alias events in new room: %s", e)
  604. async def create_room(
  605. self,
  606. requester: Requester,
  607. config: JsonDict,
  608. ratelimit: bool = True,
  609. creator_join_profile: Optional[JsonDict] = None,
  610. ) -> Tuple[str, Optional[RoomAlias], int]:
  611. """Creates a new room.
  612. Args:
  613. requester: The user who requested the room creation.
  614. config: A dict of configuration options. This will be the body of
  615. a /createRoom request; see
  616. https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3createroom
  617. ratelimit: set to False to disable the rate limiter
  618. creator_join_profile:
  619. Set to override the displayname and avatar for the creating
  620. user in this room. If unset, displayname and avatar will be
  621. derived from the user's profile. If set, should contain the
  622. values to go in the body of the 'join' event (typically
  623. `avatar_url` and/or `displayname`.
  624. Returns:
  625. A 3-tuple containing:
  626. - the room ID;
  627. - if requested, the room alias, otherwise None; and
  628. - the `stream_id` of the last persisted event.
  629. Raises:
  630. SynapseError:
  631. if the room ID couldn't be stored, 3pid invitation config
  632. validation failed, or something went horribly wrong.
  633. ResourceLimitError:
  634. if server is blocked to some resource being
  635. exceeded
  636. """
  637. user_id = requester.user.to_string()
  638. await self.auth_blocking.check_auth_blocking(requester=requester)
  639. if (
  640. self._server_notices_mxid is not None
  641. and user_id == self._server_notices_mxid
  642. ):
  643. # allow the server notices mxid to create rooms
  644. is_requester_admin = True
  645. else:
  646. is_requester_admin = await self.auth.is_server_admin(requester)
  647. # Let the third party rules modify the room creation config if needed, or abort
  648. # the room creation entirely with an exception.
  649. await self.third_party_event_rules.on_create_room(
  650. requester, config, is_requester_admin=is_requester_admin
  651. )
  652. invite_3pid_list = config.get("invite_3pid", [])
  653. invite_list = config.get("invite", [])
  654. # validate each entry for correctness
  655. for invite_3pid in invite_3pid_list:
  656. if not all(
  657. key in invite_3pid
  658. for key in ("medium", "address", "id_server", "id_access_token")
  659. ):
  660. raise SynapseError(
  661. HTTPStatus.BAD_REQUEST,
  662. "all of `medium`, `address`, `id_server` and `id_access_token` "
  663. "are required when making a 3pid invite",
  664. Codes.MISSING_PARAM,
  665. )
  666. if not is_requester_admin:
  667. spam_check = await self.spam_checker.user_may_create_room(user_id)
  668. if spam_check != NOT_SPAM:
  669. raise SynapseError(
  670. 403,
  671. "You are not permitted to create rooms",
  672. errcode=spam_check[0],
  673. additional_fields=spam_check[1],
  674. )
  675. if ratelimit:
  676. # Rate limit once in advance, but don't rate limit the individual
  677. # events in the room — room creation isn't atomic and it's very
  678. # janky if half the events in the initial state don't make it because
  679. # of rate limiting.
  680. await self.request_ratelimiter.ratelimit(requester)
  681. room_version_id = config.get(
  682. "room_version", self.config.server.default_room_version.identifier
  683. )
  684. if not isinstance(room_version_id, str):
  685. raise SynapseError(400, "room_version must be a string", Codes.BAD_JSON)
  686. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  687. if room_version is None:
  688. raise SynapseError(
  689. 400,
  690. "Your homeserver does not support this room version",
  691. Codes.UNSUPPORTED_ROOM_VERSION,
  692. )
  693. room_alias = None
  694. if "room_alias_name" in config:
  695. for wchar in string.whitespace:
  696. if wchar in config["room_alias_name"]:
  697. raise SynapseError(400, "Invalid characters in room alias")
  698. if ":" in config["room_alias_name"]:
  699. # Prevent someone from trying to pass in a full alias here.
  700. # Note that it's permissible for a room alias to have multiple
  701. # hash symbols at the start (notably bridged over from IRC, too),
  702. # but the first colon in the alias is defined to separate the local
  703. # part from the server name.
  704. # (remember server names can contain port numbers, also separated
  705. # by a colon. But under no circumstances should the local part be
  706. # allowed to contain a colon!)
  707. raise SynapseError(
  708. 400,
  709. "':' is not permitted in the room alias name. "
  710. "Please note this expects a local part — 'wombat', not '#wombat:example.com'.",
  711. )
  712. room_alias = RoomAlias(config["room_alias_name"], self.hs.hostname)
  713. mapping = await self.store.get_association_from_room_alias(room_alias)
  714. if mapping:
  715. raise SynapseError(400, "Room alias already taken", Codes.ROOM_IN_USE)
  716. for i in invite_list:
  717. try:
  718. uid = UserID.from_string(i)
  719. parse_and_validate_server_name(uid.domain)
  720. except Exception:
  721. raise SynapseError(400, "Invalid user_id: %s" % (i,))
  722. if (invite_list or invite_3pid_list) and requester.shadow_banned:
  723. # We randomly sleep a bit just to annoy the requester.
  724. await self.clock.sleep(random.randint(1, 10))
  725. # Allow the request to go through, but remove any associated invites.
  726. invite_3pid_list = []
  727. invite_list = []
  728. if invite_list or invite_3pid_list:
  729. try:
  730. # If there are invites in the request, see if the ratelimiting settings
  731. # allow that number of invites to be sent from the current user.
  732. await self.room_member_handler.ratelimit_multiple_invites(
  733. requester,
  734. room_id=None,
  735. n_invites=len(invite_list) + len(invite_3pid_list),
  736. update=False,
  737. )
  738. except LimitExceededError:
  739. raise SynapseError(400, "Cannot invite so many users at once")
  740. await self.event_creation_handler.assert_accepted_privacy_policy(requester)
  741. power_level_content_override = config.get("power_level_content_override")
  742. if (
  743. power_level_content_override
  744. and "users" in power_level_content_override
  745. and user_id not in power_level_content_override["users"]
  746. ):
  747. raise SynapseError(
  748. 400,
  749. "Not a valid power_level_content_override: 'users' did not contain %s"
  750. % (user_id,),
  751. )
  752. # The spec says rooms should default to private visibility if
  753. # `visibility` is not specified.
  754. visibility = config.get("visibility", "private")
  755. is_public = visibility == "public"
  756. room_id = await self._generate_and_create_room_id(
  757. creator_id=user_id,
  758. is_public=is_public,
  759. room_version=room_version,
  760. )
  761. # Check whether this visibility value is blocked by a third party module
  762. allowed_by_third_party_rules = (
  763. await (
  764. self.third_party_event_rules.check_visibility_can_be_modified(
  765. room_id, visibility
  766. )
  767. )
  768. )
  769. if not allowed_by_third_party_rules:
  770. raise SynapseError(403, "Room visibility value not allowed.")
  771. if is_public:
  772. room_aliases = []
  773. if room_alias:
  774. room_aliases.append(room_alias.to_string())
  775. if not self.config.roomdirectory.is_publishing_room_allowed(
  776. user_id, room_id, room_aliases
  777. ):
  778. # Let's just return a generic message, as there may be all sorts of
  779. # reasons why we said no. TODO: Allow configurable error messages
  780. # per alias creation rule?
  781. raise SynapseError(403, "Not allowed to publish room")
  782. directory_handler = self.hs.get_directory_handler()
  783. if room_alias:
  784. await directory_handler.create_association(
  785. requester=requester,
  786. room_id=room_id,
  787. room_alias=room_alias,
  788. servers=[self.hs.hostname],
  789. check_membership=False,
  790. )
  791. preset_config = config.get(
  792. "preset",
  793. RoomCreationPreset.PRIVATE_CHAT
  794. if visibility == "private"
  795. else RoomCreationPreset.PUBLIC_CHAT,
  796. )
  797. raw_initial_state = config.get("initial_state", [])
  798. initial_state = OrderedDict()
  799. for val in raw_initial_state:
  800. initial_state[(val["type"], val.get("state_key", ""))] = val["content"]
  801. creation_content = config.get("creation_content", {})
  802. # override any attempt to set room versions via the creation_content
  803. creation_content["room_version"] = room_version.identifier
  804. (
  805. last_stream_id,
  806. last_sent_event_id,
  807. depth,
  808. ) = await self._send_events_for_new_room(
  809. requester,
  810. room_id,
  811. preset_config=preset_config,
  812. invite_list=invite_list,
  813. initial_state=initial_state,
  814. creation_content=creation_content,
  815. room_alias=room_alias,
  816. power_level_content_override=power_level_content_override,
  817. creator_join_profile=creator_join_profile,
  818. )
  819. if "name" in config:
  820. name = config["name"]
  821. (
  822. name_event,
  823. last_stream_id,
  824. ) = await self.event_creation_handler.create_and_send_nonmember_event(
  825. requester,
  826. {
  827. "type": EventTypes.Name,
  828. "room_id": room_id,
  829. "sender": user_id,
  830. "state_key": "",
  831. "content": {"name": name},
  832. },
  833. ratelimit=False,
  834. prev_event_ids=[last_sent_event_id],
  835. depth=depth,
  836. )
  837. last_sent_event_id = name_event.event_id
  838. depth += 1
  839. if "topic" in config:
  840. topic = config["topic"]
  841. (
  842. topic_event,
  843. last_stream_id,
  844. ) = await self.event_creation_handler.create_and_send_nonmember_event(
  845. requester,
  846. {
  847. "type": EventTypes.Topic,
  848. "room_id": room_id,
  849. "sender": user_id,
  850. "state_key": "",
  851. "content": {"topic": topic},
  852. },
  853. ratelimit=False,
  854. prev_event_ids=[last_sent_event_id],
  855. depth=depth,
  856. )
  857. last_sent_event_id = topic_event.event_id
  858. depth += 1
  859. # we avoid dropping the lock between invites, as otherwise joins can
  860. # start coming in and making the createRoom slow.
  861. #
  862. # we also don't need to check the requester's shadow-ban here, as we
  863. # have already done so above (and potentially emptied invite_list).
  864. async with self.room_member_handler.member_linearizer.queue((room_id,)):
  865. content = {}
  866. is_direct = config.get("is_direct", None)
  867. if is_direct:
  868. content["is_direct"] = is_direct
  869. for invitee in invite_list:
  870. (
  871. member_event_id,
  872. last_stream_id,
  873. ) = await self.room_member_handler.update_membership_locked(
  874. requester,
  875. UserID.from_string(invitee),
  876. room_id,
  877. "invite",
  878. ratelimit=False,
  879. content=content,
  880. new_room=True,
  881. prev_event_ids=[last_sent_event_id],
  882. depth=depth,
  883. )
  884. last_sent_event_id = member_event_id
  885. depth += 1
  886. for invite_3pid in invite_3pid_list:
  887. id_server = invite_3pid["id_server"]
  888. id_access_token = invite_3pid["id_access_token"]
  889. address = invite_3pid["address"]
  890. medium = invite_3pid["medium"]
  891. # Note that do_3pid_invite can raise a ShadowBanError, but this was
  892. # handled above by emptying invite_3pid_list.
  893. (
  894. member_event_id,
  895. last_stream_id,
  896. ) = await self.hs.get_room_member_handler().do_3pid_invite(
  897. room_id,
  898. requester.user,
  899. medium,
  900. address,
  901. id_server,
  902. requester,
  903. txn_id=None,
  904. id_access_token=id_access_token,
  905. prev_event_ids=[last_sent_event_id],
  906. depth=depth,
  907. )
  908. last_sent_event_id = member_event_id
  909. depth += 1
  910. # Always wait for room creation to propagate before returning
  911. await self._replication.wait_for_stream_position(
  912. self.hs.config.worker.events_shard_config.get_instance(room_id),
  913. "events",
  914. last_stream_id,
  915. )
  916. return room_id, room_alias, last_stream_id
  917. async def _send_events_for_new_room(
  918. self,
  919. creator: Requester,
  920. room_id: str,
  921. preset_config: str,
  922. invite_list: List[str],
  923. initial_state: MutableStateMap,
  924. creation_content: JsonDict,
  925. room_alias: Optional[RoomAlias] = None,
  926. power_level_content_override: Optional[JsonDict] = None,
  927. creator_join_profile: Optional[JsonDict] = None,
  928. ) -> Tuple[int, str, int]:
  929. """Sends the initial events into a new room. Sends the room creation, membership,
  930. and power level events into the room sequentially, then creates and batches up the
  931. rest of the events to persist as a batch to the DB.
  932. `power_level_content_override` doesn't apply when initial state has
  933. power level state event content.
  934. Rate limiting should already have been applied by this point.
  935. Returns:
  936. A tuple containing the stream ID, event ID and depth of the last
  937. event sent to the room.
  938. """
  939. creator_id = creator.user.to_string()
  940. event_keys = {"room_id": room_id, "sender": creator_id, "state_key": ""}
  941. depth = 1
  942. # the most recently created event
  943. prev_event: List[str] = []
  944. # a map of event types, state keys -> event_ids. We collect these mappings this as events are
  945. # created (but not persisted to the db) to determine state for future created events
  946. # (as this info can't be pulled from the db)
  947. state_map: MutableStateMap[str] = {}
  948. # current_state_group of last event created. Used for computing event context of
  949. # events to be batched
  950. current_state_group: Optional[int] = None
  951. def create_event_dict(etype: str, content: JsonDict, **kwargs: Any) -> JsonDict:
  952. e = {"type": etype, "content": content}
  953. e.update(event_keys)
  954. e.update(kwargs)
  955. return e
  956. async def create_event(
  957. etype: str,
  958. content: JsonDict,
  959. for_batch: bool,
  960. **kwargs: Any,
  961. ) -> Tuple[EventBase, synapse.events.snapshot.EventContext]:
  962. """
  963. Creates an event and associated event context.
  964. Args:
  965. etype: the type of event to be created
  966. content: content of the event
  967. for_batch: whether the event is being created for batch persisting. If
  968. bool for_batch is true, this will create an event using the prev_event_ids,
  969. and will create an event context for the event using the parameters state_map
  970. and current_state_group, thus these parameters must be provided in this
  971. case if for_batch is True. The subsequently created event and context
  972. are suitable for being batched up and bulk persisted to the database
  973. with other similarly created events.
  974. """
  975. nonlocal depth
  976. nonlocal prev_event
  977. event_dict = create_event_dict(etype, content, **kwargs)
  978. new_event, new_context = await self.event_creation_handler.create_event(
  979. creator,
  980. event_dict,
  981. prev_event_ids=prev_event,
  982. depth=depth,
  983. state_map=state_map,
  984. for_batch=for_batch,
  985. current_state_group=current_state_group,
  986. )
  987. depth += 1
  988. prev_event = [new_event.event_id]
  989. state_map[(new_event.type, new_event.state_key)] = new_event.event_id
  990. return new_event, new_context
  991. try:
  992. config = self._presets_dict[preset_config]
  993. except KeyError:
  994. raise SynapseError(
  995. 400, f"'{preset_config}' is not a valid preset", errcode=Codes.BAD_JSON
  996. )
  997. creation_content.update({"creator": creator_id})
  998. creation_event, creation_context = await create_event(
  999. EventTypes.Create, creation_content, False
  1000. )
  1001. logger.debug("Sending %s in new room", EventTypes.Member)
  1002. ev = await self.event_creation_handler.handle_new_client_event(
  1003. requester=creator,
  1004. events_and_context=[(creation_event, creation_context)],
  1005. ratelimit=False,
  1006. ignore_shadow_ban=True,
  1007. )
  1008. last_sent_event_id = ev.event_id
  1009. member_event_id, _ = await self.room_member_handler.update_membership(
  1010. creator,
  1011. creator.user,
  1012. room_id,
  1013. "join",
  1014. ratelimit=False,
  1015. content=creator_join_profile,
  1016. new_room=True,
  1017. prev_event_ids=[last_sent_event_id],
  1018. depth=depth,
  1019. )
  1020. prev_event = [member_event_id]
  1021. # update the depth and state map here as the membership event has been created
  1022. # through a different code path
  1023. depth += 1
  1024. state_map[(EventTypes.Member, creator.user.to_string())] = member_event_id
  1025. # we need the state group of the membership event as it is the current state group
  1026. event_to_state = (
  1027. await self._storage_controllers.state.get_state_group_for_events(
  1028. [member_event_id]
  1029. )
  1030. )
  1031. current_state_group = event_to_state[member_event_id]
  1032. events_to_send = []
  1033. # We treat the power levels override specially as this needs to be one
  1034. # of the first events that get sent into a room.
  1035. pl_content = initial_state.pop((EventTypes.PowerLevels, ""), None)
  1036. if pl_content is not None:
  1037. power_event, power_context = await create_event(
  1038. EventTypes.PowerLevels, pl_content, True
  1039. )
  1040. current_state_group = power_context._state_group
  1041. events_to_send.append((power_event, power_context))
  1042. else:
  1043. power_level_content: JsonDict = {
  1044. "users": {creator_id: 100},
  1045. "users_default": 0,
  1046. "events": {
  1047. EventTypes.Name: 50,
  1048. EventTypes.PowerLevels: 100,
  1049. EventTypes.RoomHistoryVisibility: 100,
  1050. EventTypes.CanonicalAlias: 50,
  1051. EventTypes.RoomAvatar: 50,
  1052. EventTypes.Tombstone: 100,
  1053. EventTypes.ServerACL: 100,
  1054. EventTypes.RoomEncryption: 100,
  1055. },
  1056. "events_default": 0,
  1057. "state_default": 50,
  1058. "ban": 50,
  1059. "kick": 50,
  1060. "redact": 50,
  1061. "invite": 50,
  1062. "historical": 100,
  1063. }
  1064. if config["original_invitees_have_ops"]:
  1065. for invitee in invite_list:
  1066. power_level_content["users"][invitee] = 100
  1067. # If the user supplied a preset name e.g. "private_chat",
  1068. # we apply that preset
  1069. power_level_content.update(config["power_level_content_override"])
  1070. # If the server config contains default_power_level_content_override,
  1071. # and that contains information for this room preset, apply it.
  1072. if self._default_power_level_content_override:
  1073. override = self._default_power_level_content_override.get(preset_config)
  1074. if override is not None:
  1075. power_level_content.update(override)
  1076. # Finally, if the user supplied specific permissions for this room,
  1077. # apply those.
  1078. if power_level_content_override:
  1079. power_level_content.update(power_level_content_override)
  1080. pl_event, pl_context = await create_event(
  1081. EventTypes.PowerLevels,
  1082. power_level_content,
  1083. True,
  1084. )
  1085. current_state_group = pl_context._state_group
  1086. events_to_send.append((pl_event, pl_context))
  1087. if room_alias and (EventTypes.CanonicalAlias, "") not in initial_state:
  1088. room_alias_event, room_alias_context = await create_event(
  1089. EventTypes.CanonicalAlias, {"alias": room_alias.to_string()}, True
  1090. )
  1091. current_state_group = room_alias_context._state_group
  1092. events_to_send.append((room_alias_event, room_alias_context))
  1093. if (EventTypes.JoinRules, "") not in initial_state:
  1094. join_rules_event, join_rules_context = await create_event(
  1095. EventTypes.JoinRules,
  1096. {"join_rule": config["join_rules"]},
  1097. True,
  1098. )
  1099. current_state_group = join_rules_context._state_group
  1100. events_to_send.append((join_rules_event, join_rules_context))
  1101. if (EventTypes.RoomHistoryVisibility, "") not in initial_state:
  1102. visibility_event, visibility_context = await create_event(
  1103. EventTypes.RoomHistoryVisibility,
  1104. {"history_visibility": config["history_visibility"]},
  1105. True,
  1106. )
  1107. current_state_group = visibility_context._state_group
  1108. events_to_send.append((visibility_event, visibility_context))
  1109. if config["guest_can_join"]:
  1110. if (EventTypes.GuestAccess, "") not in initial_state:
  1111. guest_access_event, guest_access_context = await create_event(
  1112. EventTypes.GuestAccess,
  1113. {EventContentFields.GUEST_ACCESS: GuestAccess.CAN_JOIN},
  1114. True,
  1115. )
  1116. current_state_group = guest_access_context._state_group
  1117. events_to_send.append((guest_access_event, guest_access_context))
  1118. for (etype, state_key), content in initial_state.items():
  1119. event, context = await create_event(
  1120. etype, content, True, state_key=state_key
  1121. )
  1122. current_state_group = context._state_group
  1123. events_to_send.append((event, context))
  1124. if config["encrypted"]:
  1125. encryption_event, encryption_context = await create_event(
  1126. EventTypes.RoomEncryption,
  1127. {"algorithm": RoomEncryptionAlgorithms.DEFAULT},
  1128. True,
  1129. state_key="",
  1130. )
  1131. events_to_send.append((encryption_event, encryption_context))
  1132. last_event = await self.event_creation_handler.handle_new_client_event(
  1133. creator,
  1134. events_to_send,
  1135. ignore_shadow_ban=True,
  1136. ratelimit=False,
  1137. )
  1138. assert last_event.internal_metadata.stream_ordering is not None
  1139. return last_event.internal_metadata.stream_ordering, last_event.event_id, depth
  1140. def _generate_room_id(self) -> str:
  1141. """Generates a random room ID.
  1142. Room IDs look like "!opaque_id:domain" and are case-sensitive as per the spec
  1143. at https://spec.matrix.org/v1.2/appendices/#room-ids-and-event-ids.
  1144. Does not check for collisions with existing rooms or prevent future calls from
  1145. returning the same room ID. To ensure the uniqueness of a new room ID, use
  1146. `_generate_and_create_room_id` instead.
  1147. Synapse's room IDs are 18 [a-zA-Z] characters long, which comes out to around
  1148. 102 bits.
  1149. Returns:
  1150. A random room ID of the form "!opaque_id:domain".
  1151. """
  1152. random_string = stringutils.random_string(18)
  1153. return RoomID(random_string, self.hs.hostname).to_string()
  1154. async def _generate_and_create_room_id(
  1155. self,
  1156. creator_id: str,
  1157. is_public: bool,
  1158. room_version: RoomVersion,
  1159. ) -> str:
  1160. # autogen room IDs and try to create it. We may clash, so just
  1161. # try a few times till one goes through, giving up eventually.
  1162. attempts = 0
  1163. while attempts < 5:
  1164. try:
  1165. gen_room_id = self._generate_room_id()
  1166. await self.store.store_room(
  1167. room_id=gen_room_id,
  1168. room_creator_user_id=creator_id,
  1169. is_public=is_public,
  1170. room_version=room_version,
  1171. )
  1172. return gen_room_id
  1173. except StoreError:
  1174. attempts += 1
  1175. raise StoreError(500, "Couldn't generate a room ID.")
  1176. class RoomContextHandler:
  1177. def __init__(self, hs: "HomeServer"):
  1178. self.hs = hs
  1179. self.auth = hs.get_auth()
  1180. self.store = hs.get_datastores().main
  1181. self._storage_controllers = hs.get_storage_controllers()
  1182. self._state_storage_controller = self._storage_controllers.state
  1183. self._relations_handler = hs.get_relations_handler()
  1184. async def get_event_context(
  1185. self,
  1186. requester: Requester,
  1187. room_id: str,
  1188. event_id: str,
  1189. limit: int,
  1190. event_filter: Optional[Filter],
  1191. use_admin_priviledge: bool = False,
  1192. ) -> Optional[EventContext]:
  1193. """Retrieves events, pagination tokens and state around a given event
  1194. in a room.
  1195. Args:
  1196. requester
  1197. room_id
  1198. event_id
  1199. limit: The maximum number of events to return in total
  1200. (excluding state).
  1201. event_filter: the filter to apply to the events returned
  1202. (excluding the target event_id)
  1203. use_admin_priviledge: if `True`, return all events, regardless
  1204. of whether `user` has access to them. To be used **ONLY**
  1205. from the admin API.
  1206. Returns:
  1207. dict, or None if the event isn't found
  1208. """
  1209. user = requester.user
  1210. if use_admin_priviledge:
  1211. await assert_user_is_admin(self.auth, requester)
  1212. before_limit = math.floor(limit / 2.0)
  1213. after_limit = limit - before_limit
  1214. is_user_in_room = await self.store.check_local_user_in_room(
  1215. user_id=user.to_string(), room_id=room_id
  1216. )
  1217. # The user is peeking if they aren't in the room already
  1218. is_peeking = not is_user_in_room
  1219. async def filter_evts(events: List[EventBase]) -> List[EventBase]:
  1220. if use_admin_priviledge:
  1221. return events
  1222. return await filter_events_for_client(
  1223. self._storage_controllers,
  1224. user.to_string(),
  1225. events,
  1226. is_peeking=is_peeking,
  1227. )
  1228. event = await self.store.get_event(
  1229. event_id, get_prev_content=True, allow_none=True
  1230. )
  1231. if not event:
  1232. return None
  1233. filtered = await filter_evts([event])
  1234. if not filtered:
  1235. raise AuthError(403, "You don't have permission to access that event.")
  1236. results = await self.store.get_events_around(
  1237. room_id, event_id, before_limit, after_limit, event_filter
  1238. )
  1239. events_before = results.events_before
  1240. events_after = results.events_after
  1241. if event_filter:
  1242. events_before = await event_filter.filter(events_before)
  1243. events_after = await event_filter.filter(events_after)
  1244. events_before = await filter_evts(events_before)
  1245. events_after = await filter_evts(events_after)
  1246. # filter_evts can return a pruned event in case the user is allowed to see that
  1247. # there's something there but not see the content, so use the event that's in
  1248. # `filtered` rather than the event we retrieved from the datastore.
  1249. event = filtered[0]
  1250. # Fetch the aggregations.
  1251. aggregations = await self._relations_handler.get_bundled_aggregations(
  1252. itertools.chain(events_before, (event,), events_after),
  1253. user.to_string(),
  1254. )
  1255. if events_after:
  1256. last_event_id = events_after[-1].event_id
  1257. else:
  1258. last_event_id = event_id
  1259. if event_filter and event_filter.lazy_load_members:
  1260. state_filter = StateFilter.from_lazy_load_member_list(
  1261. ev.sender
  1262. for ev in itertools.chain(
  1263. events_before,
  1264. (event,),
  1265. events_after,
  1266. )
  1267. )
  1268. else:
  1269. state_filter = StateFilter.all()
  1270. # XXX: why do we return the state as of the last event rather than the
  1271. # first? Shouldn't we be consistent with /sync?
  1272. # https://github.com/matrix-org/matrix-doc/issues/687
  1273. state = await self._state_storage_controller.get_state_for_events(
  1274. [last_event_id], state_filter=state_filter
  1275. )
  1276. state_events = list(state[last_event_id].values())
  1277. if event_filter:
  1278. state_events = await event_filter.filter(state_events)
  1279. # We use a dummy token here as we only care about the room portion of
  1280. # the token, which we replace.
  1281. token = StreamToken.START
  1282. return EventContext(
  1283. events_before=events_before,
  1284. event=event,
  1285. events_after=events_after,
  1286. state=state_events,
  1287. aggregations=aggregations,
  1288. start=await token.copy_and_replace(
  1289. StreamKeyType.ROOM, results.start
  1290. ).to_string(self.store),
  1291. end=await token.copy_and_replace(StreamKeyType.ROOM, results.end).to_string(
  1292. self.store
  1293. ),
  1294. )
  1295. class TimestampLookupHandler:
  1296. def __init__(self, hs: "HomeServer"):
  1297. self.server_name = hs.hostname
  1298. self.store = hs.get_datastores().main
  1299. self.state_handler = hs.get_state_handler()
  1300. self.federation_client = hs.get_federation_client()
  1301. self.federation_event_handler = hs.get_federation_event_handler()
  1302. self._storage_controllers = hs.get_storage_controllers()
  1303. async def get_event_for_timestamp(
  1304. self,
  1305. requester: Requester,
  1306. room_id: str,
  1307. timestamp: int,
  1308. direction: Direction,
  1309. ) -> Tuple[str, int]:
  1310. """Find the closest event to the given timestamp in the given direction.
  1311. If we can't find an event locally or the event we have locally is next to a gap,
  1312. it will ask other federated homeservers for an event.
  1313. Args:
  1314. requester: The user making the request according to the access token
  1315. room_id: Room to fetch the event from
  1316. timestamp: The point in time (inclusive) we should navigate from in
  1317. the given direction to find the closest event.
  1318. direction: indicates whether we should navigate forward
  1319. or backward from the given timestamp to find the closest event.
  1320. Returns:
  1321. A tuple containing the `event_id` closest to the given timestamp in
  1322. the given direction and the `origin_server_ts`.
  1323. Raises:
  1324. SynapseError if unable to find any event locally in the given direction
  1325. """
  1326. logger.debug(
  1327. "get_event_for_timestamp(room_id=%s, timestamp=%s, direction=%s) Finding closest event...",
  1328. room_id,
  1329. timestamp,
  1330. direction,
  1331. )
  1332. local_event_id = await self.store.get_event_id_for_timestamp(
  1333. room_id, timestamp, direction
  1334. )
  1335. logger.debug(
  1336. "get_event_for_timestamp: locally, we found event_id=%s closest to timestamp=%s",
  1337. local_event_id,
  1338. timestamp,
  1339. )
  1340. # Check for gaps in the history where events could be hiding in between
  1341. # the timestamp given and the event we were able to find locally
  1342. is_event_next_to_backward_gap = False
  1343. is_event_next_to_forward_gap = False
  1344. local_event = None
  1345. if local_event_id:
  1346. local_event = await self.store.get_event(
  1347. local_event_id, allow_none=False, allow_rejected=False
  1348. )
  1349. if direction == Direction.FORWARDS:
  1350. # We only need to check for a backward gap if we're looking forwards
  1351. # to ensure there is nothing in between.
  1352. is_event_next_to_backward_gap = (
  1353. await self.store.is_event_next_to_backward_gap(local_event)
  1354. )
  1355. elif direction == Direction.BACKWARDS:
  1356. # We only need to check for a forward gap if we're looking backwards
  1357. # to ensure there is nothing in between
  1358. is_event_next_to_forward_gap = (
  1359. await self.store.is_event_next_to_forward_gap(local_event)
  1360. )
  1361. # If we found a gap, we should probably ask another homeserver first
  1362. # about more history in between
  1363. if (
  1364. not local_event_id
  1365. or is_event_next_to_backward_gap
  1366. or is_event_next_to_forward_gap
  1367. ):
  1368. logger.debug(
  1369. "get_event_for_timestamp: locally, we found event_id=%s closest to timestamp=%s which is next to a gap in event history so we're asking other homeservers first",
  1370. local_event_id,
  1371. timestamp,
  1372. )
  1373. likely_domains = (
  1374. await self._storage_controllers.state.get_current_hosts_in_room_ordered(
  1375. room_id
  1376. )
  1377. )
  1378. remote_response = await self.federation_client.timestamp_to_event(
  1379. destinations=likely_domains,
  1380. room_id=room_id,
  1381. timestamp=timestamp,
  1382. direction=direction,
  1383. )
  1384. if remote_response is not None:
  1385. logger.debug(
  1386. "get_event_for_timestamp: remote_response=%s",
  1387. remote_response,
  1388. )
  1389. remote_event_id = remote_response.event_id
  1390. remote_origin_server_ts = remote_response.origin_server_ts
  1391. # Backfill this event so we can get a pagination token for
  1392. # it with `/context` and paginate `/messages` from this
  1393. # point.
  1394. pulled_pdu_info = await self.federation_event_handler.backfill_event_id(
  1395. likely_domains, room_id, remote_event_id
  1396. )
  1397. remote_event = pulled_pdu_info.pdu
  1398. # XXX: When we see that the remote server is not trustworthy,
  1399. # maybe we should not ask them first in the future.
  1400. if remote_origin_server_ts != remote_event.origin_server_ts:
  1401. logger.info(
  1402. "get_event_for_timestamp: Remote server (%s) claimed that remote_event_id=%s occured at remote_origin_server_ts=%s but that isn't true (actually occured at %s). Their claims are dubious and we should consider not trusting them.",
  1403. pulled_pdu_info.pull_origin,
  1404. remote_event_id,
  1405. remote_origin_server_ts,
  1406. remote_event.origin_server_ts,
  1407. )
  1408. # Only return the remote event if it's closer than the local event
  1409. if not local_event or (
  1410. abs(remote_event.origin_server_ts - timestamp)
  1411. < abs(local_event.origin_server_ts - timestamp)
  1412. ):
  1413. logger.info(
  1414. "get_event_for_timestamp: returning remote_event_id=%s (%s) since it's closer to timestamp=%s than local_event=%s (%s)",
  1415. remote_event_id,
  1416. remote_event.origin_server_ts,
  1417. timestamp,
  1418. local_event.event_id if local_event else None,
  1419. local_event.origin_server_ts if local_event else None,
  1420. )
  1421. return remote_event_id, remote_origin_server_ts
  1422. # To appease mypy, we have to add both of these conditions to check for
  1423. # `None`. We only expect `local_event` to be `None` when
  1424. # `local_event_id` is `None` but mypy isn't as smart and assuming as us.
  1425. if not local_event_id or not local_event:
  1426. raise SynapseError(
  1427. 404,
  1428. "Unable to find event from %s in direction %s" % (timestamp, direction),
  1429. errcode=Codes.NOT_FOUND,
  1430. )
  1431. return local_event_id, local_event.origin_server_ts
  1432. class RoomEventSource(EventSource[RoomStreamToken, EventBase]):
  1433. def __init__(self, hs: "HomeServer"):
  1434. self.store = hs.get_datastores().main
  1435. async def get_new_events(
  1436. self,
  1437. user: UserID,
  1438. from_key: RoomStreamToken,
  1439. limit: int,
  1440. room_ids: StrCollection,
  1441. is_guest: bool,
  1442. explicit_room_id: Optional[str] = None,
  1443. ) -> Tuple[List[EventBase], RoomStreamToken]:
  1444. # We just ignore the key for now.
  1445. to_key = self.get_current_key()
  1446. if from_key.topological:
  1447. logger.warning("Stream has topological part!!!! %r", from_key)
  1448. from_key = RoomStreamToken(None, from_key.stream)
  1449. app_service = self.store.get_app_service_by_user_id(user.to_string())
  1450. if app_service:
  1451. # We no longer support AS users using /sync directly.
  1452. # See https://github.com/matrix-org/matrix-doc/issues/1144
  1453. raise NotImplementedError()
  1454. else:
  1455. room_events = await self.store.get_membership_changes_for_user(
  1456. user.to_string(), from_key, to_key
  1457. )
  1458. room_to_events = await self.store.get_room_events_stream_for_rooms(
  1459. room_ids=room_ids,
  1460. from_key=from_key,
  1461. to_key=to_key,
  1462. limit=limit or 10,
  1463. order="ASC",
  1464. )
  1465. events = list(room_events)
  1466. events.extend(e for evs, _ in room_to_events.values() for e in evs)
  1467. events.sort(key=lambda e: e.internal_metadata.order)
  1468. if limit:
  1469. events[:] = events[:limit]
  1470. if events:
  1471. end_key = events[-1].internal_metadata.after
  1472. else:
  1473. end_key = to_key
  1474. return events, end_key
  1475. def get_current_key(self) -> RoomStreamToken:
  1476. return self.store.get_room_max_token()
  1477. def get_current_key_for_room(self, room_id: str) -> Awaitable[RoomStreamToken]:
  1478. return self.store.get_current_room_stream_token_for_room_id(room_id)
  1479. class ShutdownRoomResponse(TypedDict):
  1480. """
  1481. Attributes:
  1482. kicked_users: An array of users (`user_id`) that were kicked.
  1483. failed_to_kick_users:
  1484. An array of users (`user_id`) that that were not kicked.
  1485. local_aliases:
  1486. An array of strings representing the local aliases that were
  1487. migrated from the old room to the new.
  1488. new_room_id: A string representing the room ID of the new room.
  1489. """
  1490. kicked_users: List[str]
  1491. failed_to_kick_users: List[str]
  1492. local_aliases: List[str]
  1493. new_room_id: Optional[str]
  1494. class RoomShutdownHandler:
  1495. DEFAULT_MESSAGE = (
  1496. "Sharing illegal content on this server is not permitted and rooms in"
  1497. " violation will be blocked."
  1498. )
  1499. DEFAULT_ROOM_NAME = "Content Violation Notification"
  1500. def __init__(self, hs: "HomeServer"):
  1501. self.hs = hs
  1502. self.room_member_handler = hs.get_room_member_handler()
  1503. self._room_creation_handler = hs.get_room_creation_handler()
  1504. self._replication = hs.get_replication_data_handler()
  1505. self._third_party_rules = hs.get_third_party_event_rules()
  1506. self.event_creation_handler = hs.get_event_creation_handler()
  1507. self.store = hs.get_datastores().main
  1508. async def shutdown_room(
  1509. self,
  1510. room_id: str,
  1511. requester_user_id: str,
  1512. new_room_user_id: Optional[str] = None,
  1513. new_room_name: Optional[str] = None,
  1514. message: Optional[str] = None,
  1515. block: bool = False,
  1516. ) -> ShutdownRoomResponse:
  1517. """
  1518. Shuts down a room. Moves all local users and room aliases automatically
  1519. to a new room if `new_room_user_id` is set. Otherwise local users only
  1520. leave the room without any information.
  1521. The new room will be created with the user specified by the
  1522. `new_room_user_id` parameter as room administrator and will contain a
  1523. message explaining what happened. Users invited to the new room will
  1524. have power level `-10` by default, and thus be unable to speak.
  1525. The local server will only have the power to move local user and room
  1526. aliases to the new room. Users on other servers will be unaffected.
  1527. Args:
  1528. room_id: The ID of the room to shut down.
  1529. requester_user_id:
  1530. User who requested the action and put the room on the
  1531. blocking list.
  1532. new_room_user_id:
  1533. If set, a new room will be created with this user ID
  1534. as the creator and admin, and all users in the old room will be
  1535. moved into that room. If not set, no new room will be created
  1536. and the users will just be removed from the old room.
  1537. new_room_name:
  1538. A string representing the name of the room that new users will
  1539. be invited to. Defaults to `Content Violation Notification`
  1540. message:
  1541. A string containing the first message that will be sent as
  1542. `new_room_user_id` in the new room. Ideally this will clearly
  1543. convey why the original room was shut down.
  1544. Defaults to `Sharing illegal content on this server is not
  1545. permitted and rooms in violation will be blocked.`
  1546. block:
  1547. If set to `True`, users will be prevented from joining the old
  1548. room. This option can also be used to pre-emptively block a room,
  1549. even if it's unknown to this homeserver. In this case, the room
  1550. will be blocked, and no further action will be taken. If `False`,
  1551. attempting to delete an unknown room is invalid.
  1552. Defaults to `False`.
  1553. Returns: a dict containing the following keys:
  1554. kicked_users: An array of users (`user_id`) that were kicked.
  1555. failed_to_kick_users:
  1556. An array of users (`user_id`) that that were not kicked.
  1557. local_aliases:
  1558. An array of strings representing the local aliases that were
  1559. migrated from the old room to the new.
  1560. new_room_id:
  1561. A string representing the room ID of the new room, or None if
  1562. no such room was created.
  1563. """
  1564. if not new_room_name:
  1565. new_room_name = self.DEFAULT_ROOM_NAME
  1566. if not message:
  1567. message = self.DEFAULT_MESSAGE
  1568. if not RoomID.is_valid(room_id):
  1569. raise SynapseError(400, "%s is not a legal room ID" % (room_id,))
  1570. if not await self._third_party_rules.check_can_shutdown_room(
  1571. requester_user_id, room_id
  1572. ):
  1573. raise SynapseError(
  1574. 403, "Shutdown of this room is forbidden", Codes.FORBIDDEN
  1575. )
  1576. # Action the block first (even if the room doesn't exist yet)
  1577. if block:
  1578. # This will work even if the room is already blocked, but that is
  1579. # desirable in case the first attempt at blocking the room failed below.
  1580. await self.store.block_room(room_id, requester_user_id)
  1581. if not await self.store.get_room(room_id):
  1582. # if we don't know about the room, there is nothing left to do.
  1583. return {
  1584. "kicked_users": [],
  1585. "failed_to_kick_users": [],
  1586. "local_aliases": [],
  1587. "new_room_id": None,
  1588. }
  1589. if new_room_user_id is not None:
  1590. if not self.hs.is_mine_id(new_room_user_id):
  1591. raise SynapseError(
  1592. 400, "User must be our own: %s" % (new_room_user_id,)
  1593. )
  1594. room_creator_requester = create_requester(
  1595. new_room_user_id, authenticated_entity=requester_user_id
  1596. )
  1597. new_room_id, _, stream_id = await self._room_creation_handler.create_room(
  1598. room_creator_requester,
  1599. config={
  1600. "preset": RoomCreationPreset.PUBLIC_CHAT,
  1601. "name": new_room_name,
  1602. "power_level_content_override": {"users_default": -10},
  1603. },
  1604. ratelimit=False,
  1605. )
  1606. logger.info(
  1607. "Shutting down room %r, joining to new room: %r", room_id, new_room_id
  1608. )
  1609. # We now wait for the create room to come back in via replication so
  1610. # that we can assume that all the joins/invites have propagated before
  1611. # we try and auto join below.
  1612. await self._replication.wait_for_stream_position(
  1613. self.hs.config.worker.events_shard_config.get_instance(new_room_id),
  1614. "events",
  1615. stream_id,
  1616. )
  1617. else:
  1618. new_room_id = None
  1619. logger.info("Shutting down room %r", room_id)
  1620. users = await self.store.get_users_in_room(room_id)
  1621. kicked_users = []
  1622. failed_to_kick_users = []
  1623. for user_id in users:
  1624. if not self.hs.is_mine_id(user_id):
  1625. continue
  1626. logger.info("Kicking %r from %r...", user_id, room_id)
  1627. try:
  1628. # Kick users from room
  1629. target_requester = create_requester(
  1630. user_id, authenticated_entity=requester_user_id
  1631. )
  1632. _, stream_id = await self.room_member_handler.update_membership(
  1633. requester=target_requester,
  1634. target=target_requester.user,
  1635. room_id=room_id,
  1636. action=Membership.LEAVE,
  1637. content={},
  1638. ratelimit=False,
  1639. require_consent=False,
  1640. )
  1641. # Wait for leave to come in over replication before trying to forget.
  1642. await self._replication.wait_for_stream_position(
  1643. self.hs.config.worker.events_shard_config.get_instance(room_id),
  1644. "events",
  1645. stream_id,
  1646. )
  1647. await self.room_member_handler.forget(target_requester.user, room_id)
  1648. # Join users to new room
  1649. if new_room_user_id:
  1650. assert new_room_id is not None
  1651. await self.room_member_handler.update_membership(
  1652. requester=target_requester,
  1653. target=target_requester.user,
  1654. room_id=new_room_id,
  1655. action=Membership.JOIN,
  1656. content={},
  1657. ratelimit=False,
  1658. require_consent=False,
  1659. )
  1660. kicked_users.append(user_id)
  1661. except Exception:
  1662. logger.exception(
  1663. "Failed to leave old room and join new room for %r", user_id
  1664. )
  1665. failed_to_kick_users.append(user_id)
  1666. # Send message in new room and move aliases
  1667. if new_room_user_id:
  1668. await self.event_creation_handler.create_and_send_nonmember_event(
  1669. room_creator_requester,
  1670. {
  1671. "type": "m.room.message",
  1672. "content": {"body": message, "msgtype": "m.text"},
  1673. "room_id": new_room_id,
  1674. "sender": new_room_user_id,
  1675. },
  1676. ratelimit=False,
  1677. )
  1678. aliases_for_room = await self.store.get_aliases_for_room(room_id)
  1679. assert new_room_id is not None
  1680. await self.store.update_aliases_for_room(
  1681. room_id, new_room_id, requester_user_id
  1682. )
  1683. else:
  1684. aliases_for_room = []
  1685. return {
  1686. "kicked_users": kicked_users,
  1687. "failed_to_kick_users": failed_to_kick_users,
  1688. "local_aliases": list(aliases_for_room),
  1689. "new_room_id": new_room_id,
  1690. }