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.
 
 
 
 
 
 

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