room_member.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875
  1. # Copyright 2016-2020 The Matrix.org Foundation C.I.C.
  2. # Copyright 2020 Sorunome
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import abc
  16. import logging
  17. import random
  18. from http import HTTPStatus
  19. from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple
  20. from synapse import types
  21. from synapse.api.constants import (
  22. AccountDataTypes,
  23. EventContentFields,
  24. EventTypes,
  25. GuestAccess,
  26. Membership,
  27. )
  28. from synapse.api.errors import (
  29. AuthError,
  30. Codes,
  31. LimitExceededError,
  32. ShadowBanError,
  33. SynapseError,
  34. )
  35. from synapse.api.ratelimiting import Ratelimiter
  36. from synapse.event_auth import get_named_level, get_power_level_event
  37. from synapse.events import EventBase
  38. from synapse.events.snapshot import EventContext
  39. from synapse.handlers.profile import MAX_AVATAR_URL_LEN, MAX_DISPLAYNAME_LEN
  40. from synapse.types import (
  41. JsonDict,
  42. Requester,
  43. RoomAlias,
  44. RoomID,
  45. StateMap,
  46. UserID,
  47. create_requester,
  48. get_domain_from_id,
  49. )
  50. from synapse.util.async_helpers import Linearizer
  51. from synapse.util.distributor import user_left_room
  52. if TYPE_CHECKING:
  53. from synapse.server import HomeServer
  54. logger = logging.getLogger(__name__)
  55. class RoomMemberHandler(metaclass=abc.ABCMeta):
  56. # TODO(paul): This handler currently contains a messy conflation of
  57. # low-level API that works on UserID objects and so on, and REST-level
  58. # API that takes ID strings and returns pagination chunks. These concerns
  59. # ought to be separated out a lot better.
  60. def __init__(self, hs: "HomeServer"):
  61. self.hs = hs
  62. self.store = hs.get_datastores().main
  63. self.auth = hs.get_auth()
  64. self.state_handler = hs.get_state_handler()
  65. self.config = hs.config
  66. self._server_name = hs.hostname
  67. self.federation_handler = hs.get_federation_handler()
  68. self.directory_handler = hs.get_directory_handler()
  69. self.identity_handler = hs.get_identity_handler()
  70. self.registration_handler = hs.get_registration_handler()
  71. self.profile_handler = hs.get_profile_handler()
  72. self.event_creation_handler = hs.get_event_creation_handler()
  73. self.account_data_handler = hs.get_account_data_handler()
  74. self.event_auth_handler = hs.get_event_auth_handler()
  75. self.member_linearizer: Linearizer = Linearizer(name="member")
  76. self.member_as_limiter = Linearizer(max_count=10, name="member_as_limiter")
  77. self.clock = hs.get_clock()
  78. self.spam_checker = hs.get_spam_checker()
  79. self.third_party_event_rules = hs.get_third_party_event_rules()
  80. self._server_notices_mxid = self.config.servernotices.server_notices_mxid
  81. self._enable_lookup = hs.config.registration.enable_3pid_lookup
  82. self.allow_per_room_profiles = self.config.server.allow_per_room_profiles
  83. self._join_rate_limiter_local = Ratelimiter(
  84. store=self.store,
  85. clock=self.clock,
  86. rate_hz=hs.config.ratelimiting.rc_joins_local.per_second,
  87. burst_count=hs.config.ratelimiting.rc_joins_local.burst_count,
  88. )
  89. self._join_rate_limiter_remote = Ratelimiter(
  90. store=self.store,
  91. clock=self.clock,
  92. rate_hz=hs.config.ratelimiting.rc_joins_remote.per_second,
  93. burst_count=hs.config.ratelimiting.rc_joins_remote.burst_count,
  94. )
  95. self._invites_per_room_limiter = Ratelimiter(
  96. store=self.store,
  97. clock=self.clock,
  98. rate_hz=hs.config.ratelimiting.rc_invites_per_room.per_second,
  99. burst_count=hs.config.ratelimiting.rc_invites_per_room.burst_count,
  100. )
  101. self._invites_per_user_limiter = Ratelimiter(
  102. store=self.store,
  103. clock=self.clock,
  104. rate_hz=hs.config.ratelimiting.rc_invites_per_user.per_second,
  105. burst_count=hs.config.ratelimiting.rc_invites_per_user.burst_count,
  106. )
  107. self._third_party_invite_limiter = Ratelimiter(
  108. store=self.store,
  109. clock=self.clock,
  110. rate_hz=hs.config.ratelimiting.rc_third_party_invite.per_second,
  111. burst_count=hs.config.ratelimiting.rc_third_party_invite.burst_count,
  112. )
  113. self.request_ratelimiter = hs.get_request_ratelimiter()
  114. @abc.abstractmethod
  115. async def _remote_join(
  116. self,
  117. requester: Requester,
  118. remote_room_hosts: List[str],
  119. room_id: str,
  120. user: UserID,
  121. content: dict,
  122. ) -> Tuple[str, int]:
  123. """Try and join a room that this server is not in
  124. Args:
  125. requester
  126. remote_room_hosts: List of servers that can be used to join via.
  127. room_id: Room that we are trying to join
  128. user: User who is trying to join
  129. content: A dict that should be used as the content of the join event.
  130. """
  131. raise NotImplementedError()
  132. @abc.abstractmethod
  133. async def remote_knock(
  134. self,
  135. remote_room_hosts: List[str],
  136. room_id: str,
  137. user: UserID,
  138. content: dict,
  139. ) -> Tuple[str, int]:
  140. """Try and knock on a room that this server is not in
  141. Args:
  142. remote_room_hosts: List of servers that can be used to knock via.
  143. room_id: Room that we are trying to knock on.
  144. user: User who is trying to knock.
  145. content: A dict that should be used as the content of the knock event.
  146. """
  147. raise NotImplementedError()
  148. @abc.abstractmethod
  149. async def remote_reject_invite(
  150. self,
  151. invite_event_id: str,
  152. txn_id: Optional[str],
  153. requester: Requester,
  154. content: JsonDict,
  155. ) -> Tuple[str, int]:
  156. """
  157. Rejects an out-of-band invite we have received from a remote server
  158. Args:
  159. invite_event_id: ID of the invite to be rejected
  160. txn_id: optional transaction ID supplied by the client
  161. requester: user making the rejection request, according to the access token
  162. content: additional content to include in the rejection event.
  163. Normally an empty dict.
  164. Returns:
  165. event id, stream_id of the leave event
  166. """
  167. raise NotImplementedError()
  168. @abc.abstractmethod
  169. async def remote_rescind_knock(
  170. self,
  171. knock_event_id: str,
  172. txn_id: Optional[str],
  173. requester: Requester,
  174. content: JsonDict,
  175. ) -> Tuple[str, int]:
  176. """Rescind a local knock made on a remote room.
  177. Args:
  178. knock_event_id: The ID of the knock event to rescind.
  179. txn_id: An optional transaction ID supplied by the client.
  180. requester: The user making the request, according to the access token.
  181. content: The content of the generated leave event.
  182. Returns:
  183. A tuple containing (event_id, stream_id of the leave event).
  184. """
  185. raise NotImplementedError()
  186. @abc.abstractmethod
  187. async def _user_left_room(self, target: UserID, room_id: str) -> None:
  188. """Notifies distributor on master process that the user has left the
  189. room.
  190. Args:
  191. target
  192. room_id
  193. """
  194. raise NotImplementedError()
  195. @abc.abstractmethod
  196. async def forget(self, user: UserID, room_id: str) -> None:
  197. raise NotImplementedError()
  198. async def ratelimit_multiple_invites(
  199. self,
  200. requester: Optional[Requester],
  201. room_id: Optional[str],
  202. n_invites: int,
  203. update: bool = True,
  204. ) -> None:
  205. """Ratelimit more than one invite sent by the given requester in the given room.
  206. Args:
  207. requester: The requester sending the invites.
  208. room_id: The room the invites are being sent in.
  209. n_invites: The amount of invites to ratelimit for.
  210. update: Whether to update the ratelimiter's cache.
  211. Raises:
  212. LimitExceededError: The requester can't send that many invites in the room.
  213. """
  214. await self._invites_per_room_limiter.ratelimit(
  215. requester,
  216. room_id,
  217. update=update,
  218. n_actions=n_invites,
  219. )
  220. async def ratelimit_invite(
  221. self,
  222. requester: Optional[Requester],
  223. room_id: Optional[str],
  224. invitee_user_id: str,
  225. ) -> None:
  226. """Ratelimit invites by room and by target user.
  227. If room ID is missing then we just rate limit by target user.
  228. """
  229. if room_id:
  230. await self._invites_per_room_limiter.ratelimit(requester, room_id)
  231. await self._invites_per_user_limiter.ratelimit(requester, invitee_user_id)
  232. async def _local_membership_update(
  233. self,
  234. requester: Requester,
  235. target: UserID,
  236. room_id: str,
  237. membership: str,
  238. allow_no_prev_events: bool = False,
  239. prev_event_ids: Optional[List[str]] = None,
  240. state_event_ids: Optional[List[str]] = None,
  241. txn_id: Optional[str] = None,
  242. ratelimit: bool = True,
  243. content: Optional[dict] = None,
  244. require_consent: bool = True,
  245. outlier: bool = False,
  246. historical: bool = False,
  247. ) -> Tuple[str, int]:
  248. """
  249. Internal membership update function to get an existing event or create
  250. and persist a new event for the new membership change.
  251. Args:
  252. requester:
  253. target:
  254. room_id:
  255. membership:
  256. allow_no_prev_events: Whether to allow this event to be created an empty
  257. list of prev_events. Normally this is prohibited just because most
  258. events should have a prev_event and we should only use this in special
  259. cases like MSC2716.
  260. prev_event_ids: The event IDs to use as the prev events
  261. state_event_ids:
  262. The full state at a given event. This is used particularly by the MSC2716
  263. /batch_send endpoint. One use case is the historical `state_events_at_start`;
  264. since each is marked as an `outlier`, the `EventContext.for_outlier()` won't
  265. have any `state_ids` set and therefore can't derive any state even though the
  266. prev_events are set so we need to set them ourself via this argument.
  267. This should normally be left as None, which will cause the auth_event_ids
  268. to be calculated based on the room state at the prev_events.
  269. txn_id:
  270. ratelimit:
  271. content:
  272. require_consent:
  273. outlier: Indicates whether the event is an `outlier`, i.e. if
  274. it's from an arbitrary point and floating in the DAG as
  275. opposed to being inline with the current DAG.
  276. historical: Indicates whether the message is being inserted
  277. back in time around some existing events. This is used to skip
  278. a few checks and mark the event as backfilled.
  279. Returns:
  280. Tuple of event ID and stream ordering position
  281. """
  282. user_id = target.to_string()
  283. if content is None:
  284. content = {}
  285. content["membership"] = membership
  286. if requester.is_guest:
  287. content["kind"] = "guest"
  288. # Check if we already have an event with a matching transaction ID. (We
  289. # do this check just before we persist an event as well, but may as well
  290. # do it up front for efficiency.)
  291. if txn_id and requester.access_token_id:
  292. existing_event_id = await self.store.get_event_id_from_transaction_id(
  293. room_id,
  294. requester.user.to_string(),
  295. requester.access_token_id,
  296. txn_id,
  297. )
  298. if existing_event_id:
  299. event_pos = await self.store.get_position_for_event(existing_event_id)
  300. return existing_event_id, event_pos.stream
  301. event, context = await self.event_creation_handler.create_event(
  302. requester,
  303. {
  304. "type": EventTypes.Member,
  305. "content": content,
  306. "room_id": room_id,
  307. "sender": requester.user.to_string(),
  308. "state_key": user_id,
  309. # For backwards compatibility:
  310. "membership": membership,
  311. },
  312. txn_id=txn_id,
  313. allow_no_prev_events=allow_no_prev_events,
  314. prev_event_ids=prev_event_ids,
  315. state_event_ids=state_event_ids,
  316. require_consent=require_consent,
  317. outlier=outlier,
  318. historical=historical,
  319. )
  320. prev_state_ids = await context.get_prev_state_ids()
  321. prev_member_event_id = prev_state_ids.get((EventTypes.Member, user_id), None)
  322. if event.membership == Membership.JOIN:
  323. newly_joined = True
  324. if prev_member_event_id:
  325. prev_member_event = await self.store.get_event(prev_member_event_id)
  326. newly_joined = prev_member_event.membership != Membership.JOIN
  327. # Only rate-limit if the user actually joined the room, otherwise we'll end
  328. # up blocking profile updates.
  329. if newly_joined and ratelimit:
  330. time_now_s = self.clock.time()
  331. (
  332. allowed,
  333. time_allowed,
  334. ) = await self._join_rate_limiter_local.can_do_action(requester)
  335. if not allowed:
  336. raise LimitExceededError(
  337. retry_after_ms=int(1000 * (time_allowed - time_now_s))
  338. )
  339. result_event = await self.event_creation_handler.handle_new_client_event(
  340. requester,
  341. event,
  342. context,
  343. extra_users=[target],
  344. ratelimit=ratelimit,
  345. )
  346. if event.membership == Membership.LEAVE:
  347. if prev_member_event_id:
  348. prev_member_event = await self.store.get_event(prev_member_event_id)
  349. if prev_member_event.membership == Membership.JOIN:
  350. await self._user_left_room(target, room_id)
  351. # we know it was persisted, so should have a stream ordering
  352. assert result_event.internal_metadata.stream_ordering
  353. return result_event.event_id, result_event.internal_metadata.stream_ordering
  354. async def copy_room_tags_and_direct_to_room(
  355. self, old_room_id: str, new_room_id: str, user_id: str
  356. ) -> None:
  357. """Copies the tags and direct room state from one room to another.
  358. Args:
  359. old_room_id: The room ID of the old room.
  360. new_room_id: The room ID of the new room.
  361. user_id: The user's ID.
  362. """
  363. # Retrieve user account data for predecessor room
  364. user_account_data, _ = await self.store.get_account_data_for_user(user_id)
  365. # Copy direct message state if applicable
  366. direct_rooms = user_account_data.get(AccountDataTypes.DIRECT, {})
  367. # Check which key this room is under
  368. if isinstance(direct_rooms, dict):
  369. for key, room_id_list in direct_rooms.items():
  370. if old_room_id in room_id_list and new_room_id not in room_id_list:
  371. # Add new room_id to this key
  372. direct_rooms[key].append(new_room_id)
  373. # Save back to user's m.direct account data
  374. await self.account_data_handler.add_account_data_for_user(
  375. user_id, AccountDataTypes.DIRECT, direct_rooms
  376. )
  377. break
  378. # Copy room tags if applicable
  379. room_tags = await self.store.get_tags_for_room(user_id, old_room_id)
  380. # Copy each room tag to the new room
  381. for tag, tag_content in room_tags.items():
  382. await self.account_data_handler.add_tag_to_room(
  383. user_id, new_room_id, tag, tag_content
  384. )
  385. async def update_membership(
  386. self,
  387. requester: Requester,
  388. target: UserID,
  389. room_id: str,
  390. action: str,
  391. txn_id: Optional[str] = None,
  392. remote_room_hosts: Optional[List[str]] = None,
  393. third_party_signed: Optional[dict] = None,
  394. ratelimit: bool = True,
  395. content: Optional[dict] = None,
  396. new_room: bool = False,
  397. require_consent: bool = True,
  398. outlier: bool = False,
  399. historical: bool = False,
  400. allow_no_prev_events: bool = False,
  401. prev_event_ids: Optional[List[str]] = None,
  402. state_event_ids: Optional[List[str]] = None,
  403. ) -> Tuple[str, int]:
  404. """Update a user's membership in a room.
  405. Params:
  406. requester: The user who is performing the update.
  407. target: The user whose membership is being updated.
  408. room_id: The room ID whose membership is being updated.
  409. action: The membership change, see synapse.api.constants.Membership.
  410. txn_id: The transaction ID, if given.
  411. remote_room_hosts: Remote servers to send the update to.
  412. third_party_signed: Information from a 3PID invite.
  413. ratelimit: Whether to rate limit the request.
  414. content: The content of the created event.
  415. new_room: Whether the membership update is happening in the context of a room
  416. creation.
  417. require_consent: Whether consent is required.
  418. outlier: Indicates whether the event is an `outlier`, i.e. if
  419. it's from an arbitrary point and floating in the DAG as
  420. opposed to being inline with the current DAG.
  421. historical: Indicates whether the message is being inserted
  422. back in time around some existing events. This is used to skip
  423. a few checks and mark the event as backfilled.
  424. allow_no_prev_events: Whether to allow this event to be created an empty
  425. list of prev_events. Normally this is prohibited just because most
  426. events should have a prev_event and we should only use this in special
  427. cases like MSC2716.
  428. prev_event_ids: The event IDs to use as the prev events
  429. state_event_ids:
  430. The full state at a given event. This is used particularly by the MSC2716
  431. /batch_send endpoint. One use case is the historical `state_events_at_start`;
  432. since each is marked as an `outlier`, the `EventContext.for_outlier()` won't
  433. have any `state_ids` set and therefore can't derive any state even though the
  434. prev_events are set so we need to set them ourself via this argument.
  435. This should normally be left as None, which will cause the auth_event_ids
  436. to be calculated based on the room state at the prev_events.
  437. Returns:
  438. A tuple of the new event ID and stream ID.
  439. Raises:
  440. ShadowBanError if a shadow-banned requester attempts to send an invite.
  441. """
  442. if action == Membership.INVITE and requester.shadow_banned:
  443. # We randomly sleep a bit just to annoy the requester.
  444. await self.clock.sleep(random.randint(1, 10))
  445. raise ShadowBanError()
  446. key = (room_id,)
  447. as_id = object()
  448. if requester.app_service:
  449. as_id = requester.app_service.id
  450. # We first linearise by the application service (to try to limit concurrent joins
  451. # by application services), and then by room ID.
  452. async with self.member_as_limiter.queue(as_id):
  453. async with self.member_linearizer.queue(key):
  454. result = await self.update_membership_locked(
  455. requester,
  456. target,
  457. room_id,
  458. action,
  459. txn_id=txn_id,
  460. remote_room_hosts=remote_room_hosts,
  461. third_party_signed=third_party_signed,
  462. ratelimit=ratelimit,
  463. content=content,
  464. new_room=new_room,
  465. require_consent=require_consent,
  466. outlier=outlier,
  467. historical=historical,
  468. allow_no_prev_events=allow_no_prev_events,
  469. prev_event_ids=prev_event_ids,
  470. state_event_ids=state_event_ids,
  471. )
  472. return result
  473. async def update_membership_locked(
  474. self,
  475. requester: Requester,
  476. target: UserID,
  477. room_id: str,
  478. action: str,
  479. txn_id: Optional[str] = None,
  480. remote_room_hosts: Optional[List[str]] = None,
  481. third_party_signed: Optional[dict] = None,
  482. ratelimit: bool = True,
  483. content: Optional[dict] = None,
  484. new_room: bool = False,
  485. require_consent: bool = True,
  486. outlier: bool = False,
  487. historical: bool = False,
  488. allow_no_prev_events: bool = False,
  489. prev_event_ids: Optional[List[str]] = None,
  490. state_event_ids: Optional[List[str]] = None,
  491. ) -> Tuple[str, int]:
  492. """Helper for update_membership.
  493. Assumes that the membership linearizer is already held for the room.
  494. Args:
  495. requester:
  496. target:
  497. room_id:
  498. action:
  499. txn_id:
  500. remote_room_hosts:
  501. third_party_signed:
  502. ratelimit:
  503. content:
  504. new_room: Whether the membership update is happening in the context of a room
  505. creation.
  506. require_consent:
  507. outlier: Indicates whether the event is an `outlier`, i.e. if
  508. it's from an arbitrary point and floating in the DAG as
  509. opposed to being inline with the current DAG.
  510. historical: Indicates whether the message is being inserted
  511. back in time around some existing events. This is used to skip
  512. a few checks and mark the event as backfilled.
  513. allow_no_prev_events: Whether to allow this event to be created an empty
  514. list of prev_events. Normally this is prohibited just because most
  515. events should have a prev_event and we should only use this in special
  516. cases like MSC2716.
  517. prev_event_ids: The event IDs to use as the prev events
  518. state_event_ids:
  519. The full state at a given event. This is used particularly by the MSC2716
  520. /batch_send endpoint. One use case is the historical `state_events_at_start`;
  521. since each is marked as an `outlier`, the `EventContext.for_outlier()` won't
  522. have any `state_ids` set and therefore can't derive any state even though the
  523. prev_events are set so we need to set them ourself via this argument.
  524. This should normally be left as None, which will cause the auth_event_ids
  525. to be calculated based on the room state at the prev_events.
  526. Returns:
  527. A tuple of the new event ID and stream ID.
  528. """
  529. content_specified = bool(content)
  530. if content is None:
  531. content = {}
  532. else:
  533. # We do a copy here as we potentially change some keys
  534. # later on.
  535. content = dict(content)
  536. # allow the server notices mxid to set room-level profile
  537. is_requester_server_notices_user = (
  538. self._server_notices_mxid is not None
  539. and requester.user.to_string() == self._server_notices_mxid
  540. )
  541. if (
  542. not self.allow_per_room_profiles and not is_requester_server_notices_user
  543. ) or requester.shadow_banned:
  544. # Strip profile data, knowing that new profile data will be added to the
  545. # event's content in event_creation_handler.create_event() using the target's
  546. # global profile.
  547. content.pop("displayname", None)
  548. content.pop("avatar_url", None)
  549. if len(content.get("displayname") or "") > MAX_DISPLAYNAME_LEN:
  550. raise SynapseError(
  551. 400,
  552. f"Displayname is too long (max {MAX_DISPLAYNAME_LEN})",
  553. errcode=Codes.BAD_JSON,
  554. )
  555. if len(content.get("avatar_url") or "") > MAX_AVATAR_URL_LEN:
  556. raise SynapseError(
  557. 400,
  558. f"Avatar URL is too long (max {MAX_AVATAR_URL_LEN})",
  559. errcode=Codes.BAD_JSON,
  560. )
  561. if "avatar_url" in content:
  562. if not await self.profile_handler.check_avatar_size_and_mime_type(
  563. content["avatar_url"],
  564. ):
  565. raise SynapseError(403, "This avatar is not allowed", Codes.FORBIDDEN)
  566. # The event content should *not* include the authorising user as
  567. # it won't be properly signed. Strip it out since it might come
  568. # back from a client updating a display name / avatar.
  569. #
  570. # This only applies to restricted rooms, but there should be no reason
  571. # for a client to include it. Unconditionally remove it.
  572. content.pop(EventContentFields.AUTHORISING_USER, None)
  573. effective_membership_state = action
  574. if action in ["kick", "unban"]:
  575. effective_membership_state = "leave"
  576. # if this is a join with a 3pid signature, we may need to turn a 3pid
  577. # invite into a normal invite before we can handle the join.
  578. if third_party_signed is not None:
  579. await self.federation_handler.exchange_third_party_invite(
  580. third_party_signed["sender"],
  581. target.to_string(),
  582. room_id,
  583. third_party_signed,
  584. )
  585. if not remote_room_hosts:
  586. remote_room_hosts = []
  587. if effective_membership_state not in ("leave", "ban"):
  588. is_blocked = await self.store.is_room_blocked(room_id)
  589. if is_blocked:
  590. raise SynapseError(403, "This room has been blocked on this server")
  591. if effective_membership_state == Membership.INVITE:
  592. target_id = target.to_string()
  593. if ratelimit:
  594. await self.ratelimit_invite(requester, room_id, target_id)
  595. # block any attempts to invite the server notices mxid
  596. if target_id == self._server_notices_mxid:
  597. raise SynapseError(HTTPStatus.FORBIDDEN, "Cannot invite this user")
  598. block_invite = False
  599. if (
  600. self._server_notices_mxid is not None
  601. and requester.user.to_string() == self._server_notices_mxid
  602. ):
  603. # allow the server notices mxid to send invites
  604. is_requester_admin = True
  605. else:
  606. is_requester_admin = await self.auth.is_server_admin(requester.user)
  607. if not is_requester_admin:
  608. if self.config.server.block_non_admin_invites:
  609. logger.info(
  610. "Blocking invite: user is not admin and non-admin "
  611. "invites disabled"
  612. )
  613. block_invite = True
  614. if not await self.spam_checker.user_may_invite(
  615. requester.user.to_string(), target_id, room_id
  616. ):
  617. logger.info("Blocking invite due to spam checker")
  618. block_invite = True
  619. if block_invite:
  620. raise SynapseError(403, "Invites have been disabled on this server")
  621. # An empty prev_events list is allowed as long as the auth_event_ids are present
  622. if prev_event_ids is not None:
  623. return await self._local_membership_update(
  624. requester=requester,
  625. target=target,
  626. room_id=room_id,
  627. membership=effective_membership_state,
  628. txn_id=txn_id,
  629. ratelimit=ratelimit,
  630. allow_no_prev_events=allow_no_prev_events,
  631. prev_event_ids=prev_event_ids,
  632. state_event_ids=state_event_ids,
  633. content=content,
  634. require_consent=require_consent,
  635. outlier=outlier,
  636. historical=historical,
  637. )
  638. latest_event_ids = await self.store.get_prev_events_for_room(room_id)
  639. current_state_ids = await self.state_handler.get_current_state_ids(
  640. room_id, latest_event_ids=latest_event_ids
  641. )
  642. # TODO: Refactor into dictionary of explicitly allowed transitions
  643. # between old and new state, with specific error messages for some
  644. # transitions and generic otherwise
  645. old_state_id = current_state_ids.get((EventTypes.Member, target.to_string()))
  646. if old_state_id:
  647. old_state = await self.store.get_event(old_state_id, allow_none=True)
  648. old_membership = old_state.content.get("membership") if old_state else None
  649. if action == "unban" and old_membership != "ban":
  650. raise SynapseError(
  651. 403,
  652. "Cannot unban user who was not banned"
  653. " (membership=%s)" % old_membership,
  654. errcode=Codes.BAD_STATE,
  655. )
  656. if old_membership == "ban" and action not in ["ban", "unban", "leave"]:
  657. raise SynapseError(
  658. 403,
  659. "Cannot %s user who was banned" % (action,),
  660. errcode=Codes.BAD_STATE,
  661. )
  662. if old_state:
  663. same_content = content == old_state.content
  664. same_membership = old_membership == effective_membership_state
  665. same_sender = requester.user.to_string() == old_state.sender
  666. if same_sender and same_membership and same_content:
  667. # duplicate event.
  668. # we know it was persisted, so must have a stream ordering.
  669. assert old_state.internal_metadata.stream_ordering
  670. return (
  671. old_state.event_id,
  672. old_state.internal_metadata.stream_ordering,
  673. )
  674. if old_membership in ["ban", "leave"] and action == "kick":
  675. raise AuthError(403, "The target user is not in the room")
  676. # we don't allow people to reject invites to the server notice
  677. # room, but they can leave it once they are joined.
  678. if (
  679. old_membership == Membership.INVITE
  680. and effective_membership_state == Membership.LEAVE
  681. ):
  682. is_blocked = await self._is_server_notice_room(room_id)
  683. if is_blocked:
  684. raise SynapseError(
  685. HTTPStatus.FORBIDDEN,
  686. "You cannot reject this invite",
  687. errcode=Codes.CANNOT_LEAVE_SERVER_NOTICE_ROOM,
  688. )
  689. else:
  690. if action == "kick":
  691. raise AuthError(403, "The target user is not in the room")
  692. is_host_in_room = await self._is_host_in_room(current_state_ids)
  693. if effective_membership_state == Membership.JOIN:
  694. if requester.is_guest:
  695. guest_can_join = await self._can_guest_join(current_state_ids)
  696. if not guest_can_join:
  697. # This should be an auth check, but guests are a local concept,
  698. # so don't really fit into the general auth process.
  699. raise AuthError(403, "Guest access not allowed")
  700. # Figure out whether the user is a server admin to determine whether they
  701. # should be able to bypass the spam checker.
  702. if (
  703. self._server_notices_mxid is not None
  704. and requester.user.to_string() == self._server_notices_mxid
  705. ):
  706. # allow the server notices mxid to join rooms
  707. bypass_spam_checker = True
  708. else:
  709. bypass_spam_checker = await self.auth.is_server_admin(requester.user)
  710. inviter = await self._get_inviter(target.to_string(), room_id)
  711. if (
  712. not bypass_spam_checker
  713. # We assume that if the spam checker allowed the user to create
  714. # a room then they're allowed to join it.
  715. and not new_room
  716. and not await self.spam_checker.user_may_join_room(
  717. target.to_string(), room_id, is_invited=inviter is not None
  718. )
  719. ):
  720. raise SynapseError(403, "Not allowed to join this room")
  721. # Check if a remote join should be performed.
  722. remote_join, remote_room_hosts = await self._should_perform_remote_join(
  723. target.to_string(), room_id, remote_room_hosts, content, is_host_in_room
  724. )
  725. if remote_join:
  726. if ratelimit:
  727. time_now_s = self.clock.time()
  728. (
  729. allowed,
  730. time_allowed,
  731. ) = await self._join_rate_limiter_remote.can_do_action(
  732. requester,
  733. )
  734. if not allowed:
  735. raise LimitExceededError(
  736. retry_after_ms=int(1000 * (time_allowed - time_now_s))
  737. )
  738. inviter = await self._get_inviter(target.to_string(), room_id)
  739. if inviter and not self.hs.is_mine(inviter):
  740. remote_room_hosts.append(inviter.domain)
  741. content["membership"] = Membership.JOIN
  742. profile = self.profile_handler
  743. if not content_specified:
  744. content["displayname"] = await profile.get_displayname(target)
  745. content["avatar_url"] = await profile.get_avatar_url(target)
  746. if requester.is_guest:
  747. content["kind"] = "guest"
  748. remote_join_response = await self._remote_join(
  749. requester, remote_room_hosts, room_id, target, content
  750. )
  751. return remote_join_response
  752. elif effective_membership_state == Membership.LEAVE:
  753. if not is_host_in_room:
  754. # Figure out the user's current membership state for the room
  755. (
  756. current_membership_type,
  757. current_membership_event_id,
  758. ) = await self.store.get_local_current_membership_for_user_in_room(
  759. target.to_string(), room_id
  760. )
  761. if not current_membership_type or not current_membership_event_id:
  762. logger.info(
  763. "%s sent a leave request to %s, but that is not an active room "
  764. "on this server, or there is no pending invite or knock",
  765. target,
  766. room_id,
  767. )
  768. raise SynapseError(404, "Not a known room")
  769. # perhaps we've been invited
  770. if current_membership_type == Membership.INVITE:
  771. invite = await self.store.get_event(current_membership_event_id)
  772. logger.info(
  773. "%s rejects invite to %s from %s",
  774. target,
  775. room_id,
  776. invite.sender,
  777. )
  778. if not self.hs.is_mine_id(invite.sender):
  779. # send the rejection to the inviter's HS (with fallback to
  780. # local event)
  781. return await self.remote_reject_invite(
  782. invite.event_id,
  783. txn_id,
  784. requester,
  785. content,
  786. )
  787. # the inviter was on our server, but has now left. Carry on
  788. # with the normal rejection codepath, which will also send the
  789. # rejection out to any other servers we believe are still in the room.
  790. # thanks to overzealous cleaning up of event_forward_extremities in
  791. # `delete_old_current_state_events`, it's possible to end up with no
  792. # forward extremities here. If that happens, let's just hang the
  793. # rejection off the invite event.
  794. #
  795. # see: https://github.com/matrix-org/synapse/issues/7139
  796. if len(latest_event_ids) == 0:
  797. latest_event_ids = [invite.event_id]
  798. # or perhaps this is a remote room that a local user has knocked on
  799. elif current_membership_type == Membership.KNOCK:
  800. knock = await self.store.get_event(current_membership_event_id)
  801. return await self.remote_rescind_knock(
  802. knock.event_id, txn_id, requester, content
  803. )
  804. elif effective_membership_state == Membership.KNOCK:
  805. if not is_host_in_room:
  806. # The knock needs to be sent over federation instead
  807. remote_room_hosts.append(get_domain_from_id(room_id))
  808. content["membership"] = Membership.KNOCK
  809. profile = self.profile_handler
  810. if "displayname" not in content:
  811. content["displayname"] = await profile.get_displayname(target)
  812. if "avatar_url" not in content:
  813. content["avatar_url"] = await profile.get_avatar_url(target)
  814. return await self.remote_knock(
  815. remote_room_hosts, room_id, target, content
  816. )
  817. return await self._local_membership_update(
  818. requester=requester,
  819. target=target,
  820. room_id=room_id,
  821. membership=effective_membership_state,
  822. txn_id=txn_id,
  823. ratelimit=ratelimit,
  824. prev_event_ids=latest_event_ids,
  825. state_event_ids=state_event_ids,
  826. content=content,
  827. require_consent=require_consent,
  828. outlier=outlier,
  829. )
  830. async def _should_perform_remote_join(
  831. self,
  832. user_id: str,
  833. room_id: str,
  834. remote_room_hosts: List[str],
  835. content: JsonDict,
  836. is_host_in_room: bool,
  837. ) -> Tuple[bool, List[str]]:
  838. """
  839. Check whether the server should do a remote join (as opposed to a local
  840. join) for a user.
  841. Generally a remote join is used if:
  842. * The server is not yet in the room.
  843. * The server is in the room, the room has restricted join rules, the user
  844. is not joined or invited to the room, and the server does not have
  845. another user who is capable of issuing invites.
  846. Args:
  847. user_id: The user joining the room.
  848. room_id: The room being joined.
  849. remote_room_hosts: A list of remote room hosts.
  850. content: The content to use as the event body of the join. This may
  851. be modified.
  852. is_host_in_room: True if the host is in the room.
  853. Returns:
  854. A tuple of:
  855. True if a remote join should be performed. False if the join can be
  856. done locally.
  857. A list of remote room hosts to use. This is an empty list if a
  858. local join is to be done.
  859. """
  860. # If the host isn't in the room, pass through the prospective hosts.
  861. if not is_host_in_room:
  862. return True, remote_room_hosts
  863. # If the host is in the room, but not one of the authorised hosts
  864. # for restricted join rules, a remote join must be used.
  865. room_version = await self.store.get_room_version(room_id)
  866. current_state_ids = await self.store.get_current_state_ids(room_id)
  867. # If restricted join rules are not being used, a local join can always
  868. # be used.
  869. if not await self.event_auth_handler.has_restricted_join_rules(
  870. current_state_ids, room_version
  871. ):
  872. return False, []
  873. # If the user is invited to the room or already joined, the join
  874. # event can always be issued locally.
  875. prev_member_event_id = current_state_ids.get((EventTypes.Member, user_id), None)
  876. prev_member_event = None
  877. if prev_member_event_id:
  878. prev_member_event = await self.store.get_event(prev_member_event_id)
  879. if prev_member_event.membership in (
  880. Membership.JOIN,
  881. Membership.INVITE,
  882. ):
  883. return False, []
  884. # If the local host has a user who can issue invites, then a local
  885. # join can be done.
  886. #
  887. # If not, generate a new list of remote hosts based on which
  888. # can issue invites.
  889. event_map = await self.store.get_events(current_state_ids.values())
  890. current_state = {
  891. state_key: event_map[event_id]
  892. for state_key, event_id in current_state_ids.items()
  893. }
  894. allowed_servers = get_servers_from_users(
  895. get_users_which_can_issue_invite(current_state)
  896. )
  897. # If the local server is not one of allowed servers, then a remote
  898. # join must be done. Return the list of prospective servers based on
  899. # which can issue invites.
  900. if self.hs.hostname not in allowed_servers:
  901. return True, list(allowed_servers)
  902. # Ensure the member should be allowed access via membership in a room.
  903. await self.event_auth_handler.check_restricted_join_rules(
  904. current_state_ids, room_version, user_id, prev_member_event
  905. )
  906. # If this is going to be a local join, additional information must
  907. # be included in the event content in order to efficiently validate
  908. # the event.
  909. content[
  910. EventContentFields.AUTHORISING_USER
  911. ] = await self.event_auth_handler.get_user_which_could_invite(
  912. room_id,
  913. current_state_ids,
  914. )
  915. return False, []
  916. async def transfer_room_state_on_room_upgrade(
  917. self, old_room_id: str, room_id: str
  918. ) -> None:
  919. """Upon our server becoming aware of an upgraded room, either by upgrading a room
  920. ourselves or joining one, we can transfer over information from the previous room.
  921. Copies user state (tags/push rules) for every local user that was in the old room, as
  922. well as migrating the room directory state.
  923. Args:
  924. old_room_id: The ID of the old room
  925. room_id: The ID of the new room
  926. """
  927. logger.info("Transferring room state from %s to %s", old_room_id, room_id)
  928. # Find all local users that were in the old room and copy over each user's state
  929. users = await self.store.get_users_in_room(old_room_id)
  930. await self.copy_user_state_on_room_upgrade(old_room_id, room_id, users)
  931. # Add new room to the room directory if the old room was there
  932. # Remove old room from the room directory
  933. old_room = await self.store.get_room(old_room_id)
  934. if old_room is not None and old_room["is_public"]:
  935. await self.store.set_room_is_public(old_room_id, False)
  936. await self.store.set_room_is_public(room_id, True)
  937. # Transfer alias mappings in the room directory
  938. await self.store.update_aliases_for_room(old_room_id, room_id)
  939. # Check if any groups we own contain the predecessor room
  940. local_group_ids = await self.store.get_local_groups_for_room(old_room_id)
  941. for group_id in local_group_ids:
  942. # Add new the new room to those groups
  943. await self.store.add_room_to_group(
  944. group_id, room_id, old_room is not None and old_room["is_public"]
  945. )
  946. # Remove the old room from those groups
  947. await self.store.remove_room_from_group(group_id, old_room_id)
  948. async def copy_user_state_on_room_upgrade(
  949. self, old_room_id: str, new_room_id: str, user_ids: Iterable[str]
  950. ) -> None:
  951. """Copy user-specific information when they join a new room when that new room is the
  952. result of a room upgrade
  953. Args:
  954. old_room_id: The ID of upgraded room
  955. new_room_id: The ID of the new room
  956. user_ids: User IDs to copy state for
  957. """
  958. logger.debug(
  959. "Copying over room tags and push rules from %s to %s for users %s",
  960. old_room_id,
  961. new_room_id,
  962. user_ids,
  963. )
  964. for user_id in user_ids:
  965. try:
  966. # It is an upgraded room. Copy over old tags
  967. await self.copy_room_tags_and_direct_to_room(
  968. old_room_id, new_room_id, user_id
  969. )
  970. # Copy over push rules
  971. await self.store.copy_push_rules_from_room_to_room_for_user(
  972. old_room_id, new_room_id, user_id
  973. )
  974. except Exception:
  975. logger.exception(
  976. "Error copying tags and/or push rules from rooms %s to %s for user %s. "
  977. "Skipping...",
  978. old_room_id,
  979. new_room_id,
  980. user_id,
  981. )
  982. continue
  983. async def send_membership_event(
  984. self,
  985. requester: Optional[Requester],
  986. event: EventBase,
  987. context: EventContext,
  988. ratelimit: bool = True,
  989. ) -> None:
  990. """
  991. Change the membership status of a user in a room.
  992. Args:
  993. requester: The local user who requested the membership
  994. event. If None, certain checks, like whether this homeserver can
  995. act as the sender, will be skipped.
  996. event: The membership event.
  997. context: The context of the event.
  998. ratelimit: Whether to rate limit this request.
  999. Raises:
  1000. SynapseError if there was a problem changing the membership.
  1001. """
  1002. target_user = UserID.from_string(event.state_key)
  1003. room_id = event.room_id
  1004. if requester is not None:
  1005. sender = UserID.from_string(event.sender)
  1006. assert (
  1007. sender == requester.user
  1008. ), "Sender (%s) must be same as requester (%s)" % (sender, requester.user)
  1009. assert self.hs.is_mine(sender), "Sender must be our own: %s" % (sender,)
  1010. else:
  1011. requester = types.create_requester(target_user)
  1012. prev_state_ids = await context.get_prev_state_ids()
  1013. if event.membership == Membership.JOIN:
  1014. if requester.is_guest:
  1015. guest_can_join = await self._can_guest_join(prev_state_ids)
  1016. if not guest_can_join:
  1017. # This should be an auth check, but guests are a local concept,
  1018. # so don't really fit into the general auth process.
  1019. raise AuthError(403, "Guest access not allowed")
  1020. if event.membership not in (Membership.LEAVE, Membership.BAN):
  1021. is_blocked = await self.store.is_room_blocked(room_id)
  1022. if is_blocked:
  1023. raise SynapseError(403, "This room has been blocked on this server")
  1024. event = await self.event_creation_handler.handle_new_client_event(
  1025. requester, event, context, extra_users=[target_user], ratelimit=ratelimit
  1026. )
  1027. prev_member_event_id = prev_state_ids.get(
  1028. (EventTypes.Member, event.state_key), None
  1029. )
  1030. if event.membership == Membership.LEAVE:
  1031. if prev_member_event_id:
  1032. prev_member_event = await self.store.get_event(prev_member_event_id)
  1033. if prev_member_event.membership == Membership.JOIN:
  1034. await self._user_left_room(target_user, room_id)
  1035. async def _can_guest_join(self, current_state_ids: StateMap[str]) -> bool:
  1036. """
  1037. Returns whether a guest can join a room based on its current state.
  1038. """
  1039. guest_access_id = current_state_ids.get((EventTypes.GuestAccess, ""), None)
  1040. if not guest_access_id:
  1041. return False
  1042. guest_access = await self.store.get_event(guest_access_id)
  1043. return bool(
  1044. guest_access
  1045. and guest_access.content
  1046. and guest_access.content.get(EventContentFields.GUEST_ACCESS)
  1047. == GuestAccess.CAN_JOIN
  1048. )
  1049. async def kick_guest_users(self, current_state: Iterable[EventBase]) -> None:
  1050. """Kick any local guest users from the room.
  1051. This is called when the room state changes from guests allowed to not-allowed.
  1052. Params:
  1053. current_state: the current state of the room. We will iterate this to look
  1054. for guest users to kick.
  1055. """
  1056. for member_event in current_state:
  1057. try:
  1058. if member_event.type != EventTypes.Member:
  1059. continue
  1060. if not self.hs.is_mine_id(member_event.state_key):
  1061. continue
  1062. if member_event.content["membership"] not in {
  1063. Membership.JOIN,
  1064. Membership.INVITE,
  1065. }:
  1066. continue
  1067. if (
  1068. "kind" not in member_event.content
  1069. or member_event.content["kind"] != "guest"
  1070. ):
  1071. continue
  1072. # We make the user choose to leave, rather than have the
  1073. # event-sender kick them. This is partially because we don't
  1074. # need to worry about power levels, and partially because guest
  1075. # users are a concept which doesn't hugely work over federation,
  1076. # and having homeservers have their own users leave keeps more
  1077. # of that decision-making and control local to the guest-having
  1078. # homeserver.
  1079. target_user = UserID.from_string(member_event.state_key)
  1080. requester = create_requester(
  1081. target_user, is_guest=True, authenticated_entity=self._server_name
  1082. )
  1083. handler = self.hs.get_room_member_handler()
  1084. await handler.update_membership(
  1085. requester,
  1086. target_user,
  1087. member_event.room_id,
  1088. "leave",
  1089. ratelimit=False,
  1090. require_consent=False,
  1091. )
  1092. except Exception as e:
  1093. logger.exception("Error kicking guest user: %s" % (e,))
  1094. async def lookup_room_alias(
  1095. self, room_alias: RoomAlias
  1096. ) -> Tuple[RoomID, List[str]]:
  1097. """
  1098. Get the room ID associated with a room alias.
  1099. Args:
  1100. room_alias: The alias to look up.
  1101. Returns:
  1102. A tuple of:
  1103. The room ID as a RoomID object.
  1104. Hosts likely to be participating in the room ([str]).
  1105. Raises:
  1106. SynapseError if room alias could not be found.
  1107. """
  1108. directory_handler = self.directory_handler
  1109. mapping = await directory_handler.get_association(room_alias)
  1110. if not mapping:
  1111. raise SynapseError(404, "No such room alias")
  1112. room_id = mapping["room_id"]
  1113. servers = mapping["servers"]
  1114. # put the server which owns the alias at the front of the server list.
  1115. if room_alias.domain in servers:
  1116. servers.remove(room_alias.domain)
  1117. servers.insert(0, room_alias.domain)
  1118. return RoomID.from_string(room_id), servers
  1119. async def _get_inviter(self, user_id: str, room_id: str) -> Optional[UserID]:
  1120. invite = await self.store.get_invite_for_local_user_in_room(
  1121. user_id=user_id, room_id=room_id
  1122. )
  1123. if invite:
  1124. return UserID.from_string(invite.sender)
  1125. return None
  1126. async def do_3pid_invite(
  1127. self,
  1128. room_id: str,
  1129. inviter: UserID,
  1130. medium: str,
  1131. address: str,
  1132. id_server: str,
  1133. requester: Requester,
  1134. txn_id: Optional[str],
  1135. id_access_token: Optional[str] = None,
  1136. ) -> int:
  1137. """Invite a 3PID to a room.
  1138. Args:
  1139. room_id: The room to invite the 3PID to.
  1140. inviter: The user sending the invite.
  1141. medium: The 3PID's medium.
  1142. address: The 3PID's address.
  1143. id_server: The identity server to use.
  1144. requester: The user making the request.
  1145. txn_id: The transaction ID this is part of, or None if this is not
  1146. part of a transaction.
  1147. id_access_token: The optional identity server access token.
  1148. Returns:
  1149. The new stream ID.
  1150. Raises:
  1151. ShadowBanError if the requester has been shadow-banned.
  1152. """
  1153. if self.config.server.block_non_admin_invites:
  1154. is_requester_admin = await self.auth.is_server_admin(requester.user)
  1155. if not is_requester_admin:
  1156. raise SynapseError(
  1157. 403, "Invites have been disabled on this server", Codes.FORBIDDEN
  1158. )
  1159. if requester.shadow_banned:
  1160. # We randomly sleep a bit just to annoy the requester.
  1161. await self.clock.sleep(random.randint(1, 10))
  1162. raise ShadowBanError()
  1163. # We need to rate limit *before* we send out any 3PID invites, so we
  1164. # can't just rely on the standard ratelimiting of events.
  1165. await self._third_party_invite_limiter.ratelimit(requester)
  1166. can_invite = await self.third_party_event_rules.check_threepid_can_be_invited(
  1167. medium, address, room_id
  1168. )
  1169. if not can_invite:
  1170. raise SynapseError(
  1171. 403,
  1172. "This third-party identifier can not be invited in this room",
  1173. Codes.FORBIDDEN,
  1174. )
  1175. if not self._enable_lookup:
  1176. raise SynapseError(
  1177. 403, "Looking up third-party identifiers is denied from this server"
  1178. )
  1179. invitee = await self.identity_handler.lookup_3pid(
  1180. id_server, medium, address, id_access_token
  1181. )
  1182. if invitee:
  1183. # Note that update_membership with an action of "invite" can raise
  1184. # a ShadowBanError, but this was done above already.
  1185. # We don't check the invite against the spamchecker(s) here (through
  1186. # user_may_invite) because we'll do it further down the line anyway (in
  1187. # update_membership_locked).
  1188. _, stream_id = await self.update_membership(
  1189. requester, UserID.from_string(invitee), room_id, "invite", txn_id=txn_id
  1190. )
  1191. else:
  1192. # Check if the spamchecker(s) allow this invite to go through.
  1193. if not await self.spam_checker.user_may_send_3pid_invite(
  1194. inviter_userid=requester.user.to_string(),
  1195. medium=medium,
  1196. address=address,
  1197. room_id=room_id,
  1198. ):
  1199. raise SynapseError(403, "Cannot send threepid invite")
  1200. stream_id = await self._make_and_store_3pid_invite(
  1201. requester,
  1202. id_server,
  1203. medium,
  1204. address,
  1205. room_id,
  1206. inviter,
  1207. txn_id=txn_id,
  1208. id_access_token=id_access_token,
  1209. )
  1210. return stream_id
  1211. async def _make_and_store_3pid_invite(
  1212. self,
  1213. requester: Requester,
  1214. id_server: str,
  1215. medium: str,
  1216. address: str,
  1217. room_id: str,
  1218. user: UserID,
  1219. txn_id: Optional[str],
  1220. id_access_token: Optional[str] = None,
  1221. ) -> int:
  1222. room_state = await self.state_handler.get_current_state(room_id)
  1223. inviter_display_name = ""
  1224. inviter_avatar_url = ""
  1225. member_event = room_state.get((EventTypes.Member, user.to_string()))
  1226. if member_event:
  1227. inviter_display_name = member_event.content.get("displayname", "")
  1228. inviter_avatar_url = member_event.content.get("avatar_url", "")
  1229. # if user has no display name, default to their MXID
  1230. if not inviter_display_name:
  1231. inviter_display_name = user.to_string()
  1232. canonical_room_alias = ""
  1233. canonical_alias_event = room_state.get((EventTypes.CanonicalAlias, ""))
  1234. if canonical_alias_event:
  1235. canonical_room_alias = canonical_alias_event.content.get("alias", "")
  1236. room_name = ""
  1237. room_name_event = room_state.get((EventTypes.Name, ""))
  1238. if room_name_event:
  1239. room_name = room_name_event.content.get("name", "")
  1240. room_type = None
  1241. room_create_event = room_state.get((EventTypes.Create, ""))
  1242. if room_create_event:
  1243. room_type = room_create_event.content.get(EventContentFields.ROOM_TYPE)
  1244. room_join_rules = ""
  1245. join_rules_event = room_state.get((EventTypes.JoinRules, ""))
  1246. if join_rules_event:
  1247. room_join_rules = join_rules_event.content.get("join_rule", "")
  1248. room_avatar_url = ""
  1249. room_avatar_event = room_state.get((EventTypes.RoomAvatar, ""))
  1250. if room_avatar_event:
  1251. room_avatar_url = room_avatar_event.content.get("url", "")
  1252. (
  1253. token,
  1254. public_keys,
  1255. fallback_public_key,
  1256. display_name,
  1257. ) = await self.identity_handler.ask_id_server_for_third_party_invite(
  1258. requester=requester,
  1259. id_server=id_server,
  1260. medium=medium,
  1261. address=address,
  1262. room_id=room_id,
  1263. inviter_user_id=user.to_string(),
  1264. room_alias=canonical_room_alias,
  1265. room_avatar_url=room_avatar_url,
  1266. room_join_rules=room_join_rules,
  1267. room_name=room_name,
  1268. room_type=room_type,
  1269. inviter_display_name=inviter_display_name,
  1270. inviter_avatar_url=inviter_avatar_url,
  1271. id_access_token=id_access_token,
  1272. )
  1273. (
  1274. event,
  1275. stream_id,
  1276. ) = await self.event_creation_handler.create_and_send_nonmember_event(
  1277. requester,
  1278. {
  1279. "type": EventTypes.ThirdPartyInvite,
  1280. "content": {
  1281. "display_name": display_name,
  1282. "public_keys": public_keys,
  1283. # For backwards compatibility:
  1284. "key_validity_url": fallback_public_key["key_validity_url"],
  1285. "public_key": fallback_public_key["public_key"],
  1286. },
  1287. "room_id": room_id,
  1288. "sender": user.to_string(),
  1289. "state_key": token,
  1290. },
  1291. ratelimit=False,
  1292. txn_id=txn_id,
  1293. )
  1294. return stream_id
  1295. async def _is_host_in_room(self, current_state_ids: StateMap[str]) -> bool:
  1296. # Have we just created the room, and is this about to be the very
  1297. # first member event?
  1298. create_event_id = current_state_ids.get(("m.room.create", ""))
  1299. if len(current_state_ids) == 1 and create_event_id:
  1300. # We can only get here if we're in the process of creating the room
  1301. return True
  1302. for etype, state_key in current_state_ids:
  1303. if etype != EventTypes.Member or not self.hs.is_mine_id(state_key):
  1304. continue
  1305. event_id = current_state_ids[(etype, state_key)]
  1306. event = await self.store.get_event(event_id, allow_none=True)
  1307. if not event:
  1308. continue
  1309. if event.membership == Membership.JOIN:
  1310. return True
  1311. return False
  1312. async def _is_server_notice_room(self, room_id: str) -> bool:
  1313. if self._server_notices_mxid is None:
  1314. return False
  1315. user_ids = await self.store.get_users_in_room(room_id)
  1316. return self._server_notices_mxid in user_ids
  1317. class RoomMemberMasterHandler(RoomMemberHandler):
  1318. def __init__(self, hs: "HomeServer"):
  1319. super().__init__(hs)
  1320. self.distributor = hs.get_distributor()
  1321. self.distributor.declare("user_left_room")
  1322. async def _is_remote_room_too_complex(
  1323. self, room_id: str, remote_room_hosts: List[str]
  1324. ) -> Optional[bool]:
  1325. """
  1326. Check if complexity of a remote room is too great.
  1327. Args:
  1328. room_id
  1329. remote_room_hosts
  1330. Returns: bool of whether the complexity is too great, or None
  1331. if unable to be fetched
  1332. """
  1333. max_complexity = self.hs.config.server.limit_remote_rooms.complexity
  1334. complexity = await self.federation_handler.get_room_complexity(
  1335. remote_room_hosts, room_id
  1336. )
  1337. if complexity:
  1338. return complexity["v1"] > max_complexity
  1339. return None
  1340. async def _is_local_room_too_complex(self, room_id: str) -> bool:
  1341. """
  1342. Check if the complexity of a local room is too great.
  1343. Args:
  1344. room_id: The room ID to check for complexity.
  1345. """
  1346. max_complexity = self.hs.config.server.limit_remote_rooms.complexity
  1347. complexity = await self.store.get_room_complexity(room_id)
  1348. return complexity["v1"] > max_complexity
  1349. async def _remote_join(
  1350. self,
  1351. requester: Requester,
  1352. remote_room_hosts: List[str],
  1353. room_id: str,
  1354. user: UserID,
  1355. content: dict,
  1356. ) -> Tuple[str, int]:
  1357. """Implements RoomMemberHandler._remote_join"""
  1358. # filter ourselves out of remote_room_hosts: do_invite_join ignores it
  1359. # and if it is the only entry we'd like to return a 404 rather than a
  1360. # 500.
  1361. remote_room_hosts = [
  1362. host for host in remote_room_hosts if host != self.hs.hostname
  1363. ]
  1364. if len(remote_room_hosts) == 0:
  1365. raise SynapseError(404, "No known servers")
  1366. check_complexity = self.hs.config.server.limit_remote_rooms.enabled
  1367. if (
  1368. check_complexity
  1369. and self.hs.config.server.limit_remote_rooms.admins_can_join
  1370. ):
  1371. check_complexity = not await self.auth.is_server_admin(user)
  1372. if check_complexity:
  1373. # Fetch the room complexity
  1374. too_complex = await self._is_remote_room_too_complex(
  1375. room_id, remote_room_hosts
  1376. )
  1377. if too_complex is True:
  1378. raise SynapseError(
  1379. code=400,
  1380. msg=self.hs.config.server.limit_remote_rooms.complexity_error,
  1381. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  1382. )
  1383. # We don't do an auth check if we are doing an invite
  1384. # join dance for now, since we're kinda implicitly checking
  1385. # that we are allowed to join when we decide whether or not we
  1386. # need to do the invite/join dance.
  1387. event_id, stream_id = await self.federation_handler.do_invite_join(
  1388. remote_room_hosts, room_id, user.to_string(), content
  1389. )
  1390. # Check the room we just joined wasn't too large, if we didn't fetch the
  1391. # complexity of it before.
  1392. if check_complexity:
  1393. if too_complex is False:
  1394. # We checked, and we're under the limit.
  1395. return event_id, stream_id
  1396. # Check again, but with the local state events
  1397. too_complex = await self._is_local_room_too_complex(room_id)
  1398. if too_complex is False:
  1399. # We're under the limit.
  1400. return event_id, stream_id
  1401. # The room is too large. Leave.
  1402. requester = types.create_requester(
  1403. user, authenticated_entity=self._server_name
  1404. )
  1405. await self.update_membership(
  1406. requester=requester, target=user, room_id=room_id, action="leave"
  1407. )
  1408. raise SynapseError(
  1409. code=400,
  1410. msg=self.hs.config.server.limit_remote_rooms.complexity_error,
  1411. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  1412. )
  1413. return event_id, stream_id
  1414. async def remote_reject_invite(
  1415. self,
  1416. invite_event_id: str,
  1417. txn_id: Optional[str],
  1418. requester: Requester,
  1419. content: JsonDict,
  1420. ) -> Tuple[str, int]:
  1421. """
  1422. Rejects an out-of-band invite received from a remote user
  1423. Implements RoomMemberHandler.remote_reject_invite
  1424. """
  1425. invite_event = await self.store.get_event(invite_event_id)
  1426. room_id = invite_event.room_id
  1427. target_user = invite_event.state_key
  1428. # first of all, try doing a rejection via the inviting server
  1429. fed_handler = self.federation_handler
  1430. try:
  1431. inviter_id = UserID.from_string(invite_event.sender)
  1432. event, stream_id = await fed_handler.do_remotely_reject_invite(
  1433. [inviter_id.domain], room_id, target_user, content=content
  1434. )
  1435. return event.event_id, stream_id
  1436. except Exception as e:
  1437. # if we were unable to reject the invite, we will generate our own
  1438. # leave event.
  1439. #
  1440. # The 'except' clause is very broad, but we need to
  1441. # capture everything from DNS failures upwards
  1442. #
  1443. logger.warning("Failed to reject invite: %s", e)
  1444. return await self._generate_local_out_of_band_leave(
  1445. invite_event, txn_id, requester, content
  1446. )
  1447. async def remote_rescind_knock(
  1448. self,
  1449. knock_event_id: str,
  1450. txn_id: Optional[str],
  1451. requester: Requester,
  1452. content: JsonDict,
  1453. ) -> Tuple[str, int]:
  1454. """
  1455. Rescinds a local knock made on a remote room
  1456. Args:
  1457. knock_event_id: The ID of the knock event to rescind.
  1458. txn_id: The transaction ID to use.
  1459. requester: The originator of the request.
  1460. content: The content of the leave event.
  1461. Implements RoomMemberHandler.remote_rescind_knock
  1462. """
  1463. # TODO: We don't yet support rescinding knocks over federation
  1464. # as we don't know which homeserver to send it to. An obvious
  1465. # candidate is the remote homeserver we originally knocked through,
  1466. # however we don't currently store that information.
  1467. # Just rescind the knock locally
  1468. knock_event = await self.store.get_event(knock_event_id)
  1469. return await self._generate_local_out_of_band_leave(
  1470. knock_event, txn_id, requester, content
  1471. )
  1472. async def _generate_local_out_of_band_leave(
  1473. self,
  1474. previous_membership_event: EventBase,
  1475. txn_id: Optional[str],
  1476. requester: Requester,
  1477. content: JsonDict,
  1478. ) -> Tuple[str, int]:
  1479. """Generate a local leave event for a room
  1480. This can be called after we e.g fail to reject an invite via a remote server.
  1481. It generates an out-of-band membership event locally.
  1482. Args:
  1483. previous_membership_event: the previous membership event for this user
  1484. txn_id: optional transaction ID supplied by the client
  1485. requester: user making the request, according to the access token
  1486. content: additional content to include in the leave event.
  1487. Normally an empty dict.
  1488. Returns:
  1489. A tuple containing (event_id, stream_id of the leave event)
  1490. """
  1491. room_id = previous_membership_event.room_id
  1492. target_user = previous_membership_event.state_key
  1493. content["membership"] = Membership.LEAVE
  1494. event_dict = {
  1495. "type": EventTypes.Member,
  1496. "room_id": room_id,
  1497. "sender": target_user,
  1498. "content": content,
  1499. "state_key": target_user,
  1500. }
  1501. # the auth events for the new event are the same as that of the previous event, plus
  1502. # the event itself.
  1503. #
  1504. # the prev_events consist solely of the previous membership event.
  1505. prev_event_ids = [previous_membership_event.event_id]
  1506. auth_event_ids = (
  1507. list(previous_membership_event.auth_event_ids()) + prev_event_ids
  1508. )
  1509. event, context = await self.event_creation_handler.create_event(
  1510. requester,
  1511. event_dict,
  1512. txn_id=txn_id,
  1513. prev_event_ids=prev_event_ids,
  1514. auth_event_ids=auth_event_ids,
  1515. outlier=True,
  1516. )
  1517. event.internal_metadata.out_of_band_membership = True
  1518. result_event = await self.event_creation_handler.handle_new_client_event(
  1519. requester,
  1520. event,
  1521. context,
  1522. extra_users=[UserID.from_string(target_user)],
  1523. )
  1524. # we know it was persisted, so must have a stream ordering
  1525. assert result_event.internal_metadata.stream_ordering
  1526. return result_event.event_id, result_event.internal_metadata.stream_ordering
  1527. async def remote_knock(
  1528. self,
  1529. remote_room_hosts: List[str],
  1530. room_id: str,
  1531. user: UserID,
  1532. content: dict,
  1533. ) -> Tuple[str, int]:
  1534. """Sends a knock to a room. Attempts to do so via one remote out of a given list.
  1535. Args:
  1536. remote_room_hosts: A list of homeservers to try knocking through.
  1537. room_id: The ID of the room to knock on.
  1538. user: The user to knock on behalf of.
  1539. content: The content of the knock event.
  1540. Returns:
  1541. A tuple of (event ID, stream ID).
  1542. """
  1543. # filter ourselves out of remote_room_hosts
  1544. remote_room_hosts = [
  1545. host for host in remote_room_hosts if host != self.hs.hostname
  1546. ]
  1547. if len(remote_room_hosts) == 0:
  1548. raise SynapseError(404, "No known servers")
  1549. return await self.federation_handler.do_knock(
  1550. remote_room_hosts, room_id, user.to_string(), content=content
  1551. )
  1552. async def _user_left_room(self, target: UserID, room_id: str) -> None:
  1553. """Implements RoomMemberHandler._user_left_room"""
  1554. user_left_room(self.distributor, target, room_id)
  1555. async def forget(self, user: UserID, room_id: str) -> None:
  1556. user_id = user.to_string()
  1557. member = await self.state_handler.get_current_state(
  1558. room_id=room_id, event_type=EventTypes.Member, state_key=user_id
  1559. )
  1560. membership = member.membership if member else None
  1561. if membership is not None and membership not in [
  1562. Membership.LEAVE,
  1563. Membership.BAN,
  1564. ]:
  1565. raise SynapseError(400, "User %s in room %s" % (user_id, room_id))
  1566. if membership:
  1567. await self.store.forget(user_id, room_id)
  1568. def get_users_which_can_issue_invite(auth_events: StateMap[EventBase]) -> List[str]:
  1569. """
  1570. Return the list of users which can issue invites.
  1571. This is done by exploring the joined users and comparing their power levels
  1572. to the necessyar power level to issue an invite.
  1573. Args:
  1574. auth_events: state in force at this point in the room
  1575. Returns:
  1576. The users which can issue invites.
  1577. """
  1578. invite_level = get_named_level(auth_events, "invite", 0)
  1579. users_default_level = get_named_level(auth_events, "users_default", 0)
  1580. power_level_event = get_power_level_event(auth_events)
  1581. # Custom power-levels for users.
  1582. if power_level_event:
  1583. users = power_level_event.content.get("users", {})
  1584. else:
  1585. users = {}
  1586. result = []
  1587. # Check which members are able to invite by ensuring they're joined and have
  1588. # the necessary power level.
  1589. for (event_type, state_key), event in auth_events.items():
  1590. if event_type != EventTypes.Member:
  1591. continue
  1592. if event.membership != Membership.JOIN:
  1593. continue
  1594. # Check if the user has a custom power level.
  1595. if users.get(state_key, users_default_level) >= invite_level:
  1596. result.append(state_key)
  1597. return result
  1598. def get_servers_from_users(users: List[str]) -> Set[str]:
  1599. """
  1600. Resolve a list of users into their servers.
  1601. Args:
  1602. users: A list of users.
  1603. Returns:
  1604. A set of servers.
  1605. """
  1606. servers = set()
  1607. for user in users:
  1608. try:
  1609. servers.add(get_domain_from_id(user))
  1610. except SynapseError:
  1611. pass
  1612. return servers