deactivate_account.py 12 KB

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