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.
 
 
 
 
 
 

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