Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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