You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1986 lines
78 KiB

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