deactivate_account.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017, 2018 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from synapse.api.errors import SynapseError
  18. from synapse.metrics.background_process_metrics import run_as_background_process
  19. from synapse.types import UserID, create_requester
  20. from ._base import BaseHandler
  21. logger = logging.getLogger(__name__)
  22. class DeactivateAccountHandler(BaseHandler):
  23. """Handler which deals with deactivating user accounts."""
  24. def __init__(self, hs):
  25. super(DeactivateAccountHandler, self).__init__(hs)
  26. self._auth_handler = hs.get_auth_handler()
  27. self._device_handler = hs.get_device_handler()
  28. self._room_member_handler = hs.get_room_member_handler()
  29. self._identity_handler = hs.get_handlers().identity_handler
  30. self.user_directory_handler = hs.get_user_directory_handler()
  31. # Flag that indicates whether the process to part users from rooms is running
  32. self._user_parter_running = False
  33. # Start the user parter loop so it can resume parting users from rooms where
  34. # it left off (if it has work left to do).
  35. hs.get_reactor().callWhenRunning(self._start_user_parting)
  36. self._account_validity_enabled = hs.config.account_validity.enabled
  37. async def deactivate_account(self, user_id, erase_data, id_server=None):
  38. """Deactivate a user's account
  39. Args:
  40. user_id (str): ID of user to be deactivated
  41. erase_data (bool): whether to GDPR-erase the user's data
  42. id_server (str|None): Use the given identity server when unbinding
  43. any threepids. If None then will attempt to unbind using the
  44. identity server specified when binding (if known).
  45. Returns:
  46. Deferred[bool]: True if identity server supports removing
  47. threepids, otherwise False.
  48. """
  49. # FIXME: Theoretically there is a race here wherein user resets
  50. # password using threepid.
  51. # delete threepids first. We remove these from the IS so if this fails,
  52. # leave the user still active so they can try again.
  53. # Ideally we would prevent password resets and then do this in the
  54. # background thread.
  55. # This will be set to false if the identity server doesn't support
  56. # unbinding
  57. identity_server_supports_unbinding = True
  58. # Retrieve the 3PIDs this user has bound to an identity server
  59. threepids = await self.store.user_get_bound_threepids(user_id)
  60. for threepid in threepids:
  61. try:
  62. result = await self._identity_handler.try_unbind_threepid(
  63. user_id,
  64. {
  65. "medium": threepid["medium"],
  66. "address": threepid["address"],
  67. "id_server": id_server,
  68. },
  69. )
  70. identity_server_supports_unbinding &= result
  71. except Exception:
  72. # Do we want this to be a fatal error or should we carry on?
  73. logger.exception("Failed to remove threepid from ID server")
  74. raise SynapseError(400, "Failed to remove threepid from ID server")
  75. await self.store.user_delete_threepid(
  76. user_id, threepid["medium"], threepid["address"]
  77. )
  78. # Remove all 3PIDs this user has bound to the homeserver
  79. await self.store.user_delete_threepids(user_id)
  80. # delete any devices belonging to the user, which will also
  81. # delete corresponding access tokens.
  82. await self._device_handler.delete_all_devices_for_user(user_id)
  83. # then delete any remaining access tokens which weren't associated with
  84. # a device.
  85. await self._auth_handler.delete_access_tokens_for_user(user_id)
  86. await self.store.user_set_password_hash(user_id, None)
  87. # Add the user to a table of users pending deactivation (ie.
  88. # removal from all the rooms they're a member of)
  89. await self.store.add_user_pending_deactivation(user_id)
  90. # delete from user directory
  91. await self.user_directory_handler.handle_user_deactivated(user_id)
  92. # Mark the user as erased, if they asked for that
  93. if erase_data:
  94. logger.info("Marking %s as erased", user_id)
  95. await self.store.mark_user_erased(user_id)
  96. # Now start the process that goes through that list and
  97. # parts users from rooms (if it isn't already running)
  98. self._start_user_parting()
  99. # Reject all pending invites for the user, so that the user doesn't show up in the
  100. # "invited" section of rooms' members list.
  101. await self._reject_pending_invites_for_user(user_id)
  102. # Remove all information on the user from the account_validity table.
  103. if self._account_validity_enabled:
  104. await self.store.delete_account_validity_for_user(user_id)
  105. # Mark the user as deactivated.
  106. await self.store.set_user_deactivated_status(user_id, True)
  107. return identity_server_supports_unbinding
  108. async def _reject_pending_invites_for_user(self, user_id):
  109. """Reject pending invites addressed to a given user ID.
  110. Args:
  111. user_id (str): The user ID to reject pending invites for.
  112. """
  113. user = UserID.from_string(user_id)
  114. pending_invites = await self.store.get_invited_rooms_for_local_user(user_id)
  115. for room in pending_invites:
  116. try:
  117. await self._room_member_handler.update_membership(
  118. create_requester(user),
  119. user,
  120. room.room_id,
  121. "leave",
  122. ratelimit=False,
  123. require_consent=False,
  124. )
  125. logger.info(
  126. "Rejected invite for deactivated user %r in room %r",
  127. user_id,
  128. room.room_id,
  129. )
  130. except Exception:
  131. logger.exception(
  132. "Failed to reject invite for user %r in room %r:"
  133. " ignoring and continuing",
  134. user_id,
  135. room.room_id,
  136. )
  137. def _start_user_parting(self):
  138. """
  139. Start the process that goes through the table of users
  140. pending deactivation, if it isn't already running.
  141. Returns:
  142. None
  143. """
  144. if not self._user_parter_running:
  145. run_as_background_process("user_parter_loop", self._user_parter_loop)
  146. async def _user_parter_loop(self):
  147. """Loop that parts deactivated users from rooms
  148. Returns:
  149. None
  150. """
  151. self._user_parter_running = True
  152. logger.info("Starting user parter")
  153. try:
  154. while True:
  155. user_id = await self.store.get_user_pending_deactivation()
  156. if user_id is None:
  157. break
  158. logger.info("User parter parting %r", user_id)
  159. await self._part_user(user_id)
  160. await self.store.del_user_pending_deactivation(user_id)
  161. logger.info("User parter finished parting %r", user_id)
  162. logger.info("User parter finished: stopping")
  163. finally:
  164. self._user_parter_running = False
  165. async def _part_user(self, user_id):
  166. """Causes the given user_id to leave all the rooms they're joined to
  167. Returns:
  168. None
  169. """
  170. user = UserID.from_string(user_id)
  171. rooms_for_user = await self.store.get_rooms_for_user(user_id)
  172. for room_id in rooms_for_user:
  173. logger.info("User parter parting %r from %r", user_id, room_id)
  174. try:
  175. await self._room_member_handler.update_membership(
  176. create_requester(user),
  177. user,
  178. room_id,
  179. "leave",
  180. ratelimit=False,
  181. require_consent=False,
  182. )
  183. except Exception:
  184. logger.exception(
  185. "Failed to part user %r from room %r: ignoring and continuing",
  186. user_id,
  187. room_id,
  188. )