room.py 76 KB

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