room_member.py 80 KB

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