deactivate_account.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. # Copyright 2017, 2018 New Vector Ltd
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 logging
  16. from typing import TYPE_CHECKING, Optional
  17. from synapse.api.errors import SynapseError
  18. from synapse.handlers.device import DeviceHandler
  19. from synapse.metrics.background_process_metrics import run_as_background_process
  20. from synapse.types import Codes, Requester, UserID, create_requester
  21. if TYPE_CHECKING:
  22. from synapse.server import HomeServer
  23. logger = logging.getLogger(__name__)
  24. class DeactivateAccountHandler:
  25. """Handler which deals with deactivating user accounts."""
  26. def __init__(self, hs: "HomeServer"):
  27. self.store = hs.get_datastores().main
  28. self.hs = hs
  29. self._auth_handler = hs.get_auth_handler()
  30. self._device_handler = hs.get_device_handler()
  31. self._room_member_handler = hs.get_room_member_handler()
  32. self._identity_handler = hs.get_identity_handler()
  33. self._profile_handler = hs.get_profile_handler()
  34. self.user_directory_handler = hs.get_user_directory_handler()
  35. self._server_name = hs.hostname
  36. self._third_party_rules = hs.get_third_party_event_rules()
  37. # Flag that indicates whether the process to part users from rooms is running
  38. self._user_parter_running = False
  39. self._third_party_rules = hs.get_third_party_event_rules()
  40. # Start the user parter loop so it can resume parting users from rooms where
  41. # it left off (if it has work left to do).
  42. if hs.config.worker.run_background_tasks:
  43. hs.get_reactor().callWhenRunning(self._start_user_parting)
  44. self._account_validity_enabled = (
  45. hs.config.account_validity.account_validity_enabled
  46. )
  47. async def deactivate_account(
  48. self,
  49. user_id: str,
  50. erase_data: bool,
  51. requester: Requester,
  52. id_server: Optional[str] = None,
  53. by_admin: bool = False,
  54. ) -> bool:
  55. """Deactivate a user's account
  56. Args:
  57. user_id: ID of user to be deactivated
  58. erase_data: whether to GDPR-erase the user's data
  59. requester: The user attempting to make this change.
  60. id_server: Use the given identity server when unbinding
  61. any threepids. If None then will attempt to unbind using the
  62. identity server specified when binding (if known).
  63. by_admin: Whether this change was made by an administrator.
  64. Returns:
  65. True if identity server supports removing threepids, otherwise False.
  66. """
  67. # This can only be called on the main process.
  68. assert isinstance(self._device_handler, DeviceHandler)
  69. # Check if this user can be deactivated
  70. if not await self._third_party_rules.check_can_deactivate_user(
  71. user_id, by_admin
  72. ):
  73. raise SynapseError(
  74. 403, "Deactivation of this user is forbidden", Codes.FORBIDDEN
  75. )
  76. # FIXME: Theoretically there is a race here wherein user resets
  77. # password using threepid.
  78. # delete threepids first. We remove these from the IS so if this fails,
  79. # leave the user still active so they can try again.
  80. # Ideally we would prevent password resets and then do this in the
  81. # background thread.
  82. # This will be set to false if the identity server doesn't support
  83. # unbinding
  84. identity_server_supports_unbinding = True
  85. # Retrieve the 3PIDs this user has bound to an identity server
  86. threepids = await self.store.user_get_bound_threepids(user_id)
  87. for threepid in threepids:
  88. try:
  89. result = await self._identity_handler.try_unbind_threepid(
  90. user_id,
  91. {
  92. "medium": threepid["medium"],
  93. "address": threepid["address"],
  94. "id_server": id_server,
  95. },
  96. )
  97. identity_server_supports_unbinding &= result
  98. except Exception:
  99. # Do we want this to be a fatal error or should we carry on?
  100. logger.exception("Failed to remove threepid from ID server")
  101. raise SynapseError(400, "Failed to remove threepid from ID server")
  102. await self.store.user_delete_threepid(
  103. user_id, threepid["medium"], threepid["address"]
  104. )
  105. # Remove all 3PIDs this user has bound to the homeserver
  106. await self.store.user_delete_threepids(user_id)
  107. # delete any devices belonging to the user, which will also
  108. # delete corresponding access tokens.
  109. await self._device_handler.delete_all_devices_for_user(user_id)
  110. # then delete any remaining access tokens which weren't associated with
  111. # a device.
  112. await self._auth_handler.delete_access_tokens_for_user(user_id)
  113. await self.store.user_set_password_hash(user_id, None)
  114. # Most of the pushers will have been deleted when we logged out the
  115. # associated devices above, but we still need to delete pushers not
  116. # associated with devices, e.g. email pushers.
  117. await self.store.delete_all_pushers_for_user(user_id)
  118. # Add the user to a table of users pending deactivation (ie.
  119. # removal from all the rooms they're a member of)
  120. await self.store.add_user_pending_deactivation(user_id)
  121. # delete from user directory
  122. await self.user_directory_handler.handle_local_user_deactivated(user_id)
  123. # Mark the user as erased, if they asked for that
  124. if erase_data:
  125. user = UserID.from_string(user_id)
  126. # Remove avatar URL from this user
  127. await self._profile_handler.set_avatar_url(
  128. user, requester, "", by_admin, deactivation=True
  129. )
  130. # Remove displayname from this user
  131. await self._profile_handler.set_displayname(
  132. user, requester, "", by_admin, deactivation=True
  133. )
  134. logger.info("Marking %s as erased", user_id)
  135. await self.store.mark_user_erased(user_id)
  136. # Now start the process that goes through that list and
  137. # parts users from rooms (if it isn't already running)
  138. self._start_user_parting()
  139. # Reject all pending invites for the user, so that the user doesn't show up in the
  140. # "invited" section of rooms' members list.
  141. await self._reject_pending_invites_for_user(user_id)
  142. # Remove all information on the user from the account_validity table.
  143. if self._account_validity_enabled:
  144. await self.store.delete_account_validity_for_user(user_id)
  145. # Mark the user as deactivated.
  146. await self.store.set_user_deactivated_status(user_id, True)
  147. # Remove account data (including ignored users and push rules).
  148. await self.store.purge_account_data_for_user(user_id)
  149. # Let modules know the user has been deactivated.
  150. await self._third_party_rules.on_user_deactivation_status_changed(
  151. user_id,
  152. True,
  153. by_admin,
  154. )
  155. return identity_server_supports_unbinding
  156. async def _reject_pending_invites_for_user(self, user_id: str) -> None:
  157. """Reject pending invites addressed to a given user ID.
  158. Args:
  159. user_id: The user ID to reject pending invites for.
  160. """
  161. user = UserID.from_string(user_id)
  162. pending_invites = await self.store.get_invited_rooms_for_local_user(user_id)
  163. for room in pending_invites:
  164. try:
  165. await self._room_member_handler.update_membership(
  166. create_requester(user, authenticated_entity=self._server_name),
  167. user,
  168. room.room_id,
  169. "leave",
  170. ratelimit=False,
  171. require_consent=False,
  172. )
  173. logger.info(
  174. "Rejected invite for deactivated user %r in room %r",
  175. user_id,
  176. room.room_id,
  177. )
  178. except Exception:
  179. logger.exception(
  180. "Failed to reject invite for user %r in room %r:"
  181. " ignoring and continuing",
  182. user_id,
  183. room.room_id,
  184. )
  185. def _start_user_parting(self) -> None:
  186. """
  187. Start the process that goes through the table of users
  188. pending deactivation, if it isn't already running.
  189. """
  190. if not self._user_parter_running:
  191. run_as_background_process("user_parter_loop", self._user_parter_loop)
  192. async def _user_parter_loop(self) -> None:
  193. """Loop that parts deactivated users from rooms"""
  194. self._user_parter_running = True
  195. logger.info("Starting user parter")
  196. try:
  197. while True:
  198. user_id = await self.store.get_user_pending_deactivation()
  199. if user_id is None:
  200. break
  201. logger.info("User parter parting %r", user_id)
  202. await self._part_user(user_id)
  203. await self.store.del_user_pending_deactivation(user_id)
  204. logger.info("User parter finished parting %r", user_id)
  205. logger.info("User parter finished: stopping")
  206. finally:
  207. self._user_parter_running = False
  208. async def _part_user(self, user_id: str) -> None:
  209. """Causes the given user_id to leave all the rooms they're joined to"""
  210. user = UserID.from_string(user_id)
  211. rooms_for_user = await self.store.get_rooms_for_user(user_id)
  212. for room_id in rooms_for_user:
  213. logger.info("User parter parting %r from %r", user_id, room_id)
  214. try:
  215. await self._room_member_handler.update_membership(
  216. create_requester(user, authenticated_entity=self._server_name),
  217. user,
  218. room_id,
  219. "leave",
  220. ratelimit=False,
  221. require_consent=False,
  222. )
  223. except Exception:
  224. logger.exception(
  225. "Failed to part user %r from room %r: ignoring and continuing",
  226. user_id,
  227. room_id,
  228. )
  229. async def activate_account(self, user_id: str) -> None:
  230. """
  231. Activate an account that was previously deactivated.
  232. This marks the user as active and not erased in the database, but does
  233. not attempt to rejoin rooms, re-add threepids, etc.
  234. If enabled, the user will be re-added to the user directory.
  235. The user will also need a password hash set to actually login.
  236. Args:
  237. user_id: ID of user to be re-activated
  238. """
  239. user = UserID.from_string(user_id)
  240. # Ensure the user is not marked as erased.
  241. await self.store.mark_user_not_erased(user_id)
  242. # Mark the user as active.
  243. await self.store.set_user_deactivated_status(user_id, False)
  244. await self._third_party_rules.on_user_deactivation_status_changed(
  245. user_id, False, True
  246. )
  247. # Add the user to the directory, if necessary. Note that
  248. # this must be done after the user is re-activated, because
  249. # deactivated users are excluded from the user directory.
  250. profile = await self.store.get_profileinfo(user.localpart)
  251. await self.user_directory_handler.handle_local_profile_change(user_id, profile)