room.py 75 KB

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