account_validity.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. # Copyright 2019 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import email.mime.multipart
  15. import email.utils
  16. import logging
  17. from typing import TYPE_CHECKING, List, Optional, Tuple
  18. from synapse.api.errors import AuthError, StoreError, SynapseError
  19. from synapse.metrics.background_process_metrics import wrap_as_background_process
  20. from synapse.types import UserID
  21. from synapse.util import stringutils
  22. from synapse.util.async_helpers import delay_cancellation
  23. if TYPE_CHECKING:
  24. from synapse.server import HomeServer
  25. logger = logging.getLogger(__name__)
  26. class AccountValidityHandler:
  27. def __init__(self, hs: "HomeServer"):
  28. self.hs = hs
  29. self.config = hs.config
  30. self.store = hs.get_datastores().main
  31. self.send_email_handler = hs.get_send_email_handler()
  32. self.clock = hs.get_clock()
  33. self._app_name = hs.config.email.email_app_name
  34. self._module_api_callbacks = hs.get_module_api_callbacks().account_validity
  35. self._account_validity_enabled = (
  36. hs.config.account_validity.account_validity_enabled
  37. )
  38. self._account_validity_renew_by_email_enabled = (
  39. hs.config.account_validity.account_validity_renew_by_email_enabled
  40. )
  41. self._account_validity_period = None
  42. if self._account_validity_enabled:
  43. self._account_validity_period = (
  44. hs.config.account_validity.account_validity_period
  45. )
  46. if (
  47. self._account_validity_enabled
  48. and self._account_validity_renew_by_email_enabled
  49. ):
  50. # Don't do email-specific configuration if renewal by email is disabled.
  51. self._template_html = hs.config.email.account_validity_template_html
  52. self._template_text = hs.config.email.account_validity_template_text
  53. self._renew_email_subject = (
  54. hs.config.account_validity.account_validity_renew_email_subject
  55. )
  56. # Check the renewal emails to send and send them every 30min.
  57. if hs.config.worker.run_background_tasks:
  58. self.clock.looping_call(self._send_renewal_emails, 30 * 60 * 1000)
  59. async def is_user_expired(self, user_id: str) -> bool:
  60. """Checks if a user has expired against third-party modules.
  61. Args:
  62. user_id: The user to check the expiry of.
  63. Returns:
  64. Whether the user has expired.
  65. """
  66. for callback in self._module_api_callbacks.is_user_expired_callbacks:
  67. expired = await delay_cancellation(callback(user_id))
  68. if expired is not None:
  69. return expired
  70. if self._account_validity_enabled:
  71. # If no module could determine whether the user has expired and the legacy
  72. # configuration is enabled, fall back to it.
  73. return await self.store.is_account_expired(user_id, self.clock.time_msec())
  74. return False
  75. async def on_user_registration(self, user_id: str) -> None:
  76. """Tell third-party modules about a user's registration.
  77. Args:
  78. user_id: The ID of the newly registered user.
  79. """
  80. for callback in self._module_api_callbacks.on_user_registration_callbacks:
  81. await callback(user_id)
  82. async def on_user_login(
  83. self,
  84. user_id: str,
  85. auth_provider_type: Optional[str],
  86. auth_provider_id: Optional[str],
  87. ) -> None:
  88. """Tell third-party modules about a user logins.
  89. Args:
  90. user_id: The mxID of the user.
  91. auth_provider_type: The type of login.
  92. auth_provider_id: The ID of the auth provider.
  93. """
  94. for callback in self._module_api_callbacks.on_user_login_callbacks:
  95. await callback(user_id, auth_provider_type, auth_provider_id)
  96. @wrap_as_background_process("send_renewals")
  97. async def _send_renewal_emails(self) -> None:
  98. """Gets the list of users whose account is expiring in the amount of time
  99. configured in the ``renew_at`` parameter from the ``account_validity``
  100. configuration, and sends renewal emails to all of these users as long as they
  101. have an email 3PID attached to their account.
  102. """
  103. expiring_users = await self.store.get_users_expiring_soon()
  104. if expiring_users:
  105. for user_id, expiration_ts_ms in expiring_users:
  106. await self._send_renewal_email(
  107. user_id=user_id, expiration_ts=expiration_ts_ms
  108. )
  109. async def send_renewal_email_to_user(self, user_id: str) -> None:
  110. """
  111. Send a renewal email for a specific user.
  112. Args:
  113. user_id: The user ID to send a renewal email for.
  114. Raises:
  115. SynapseError if the user is not set to renew.
  116. """
  117. # If a module supports sending a renewal email from here, do that, otherwise do
  118. # the legacy dance.
  119. if self._module_api_callbacks.on_legacy_send_mail_callback is not None:
  120. await self._module_api_callbacks.on_legacy_send_mail_callback(user_id)
  121. return
  122. if not self._account_validity_renew_by_email_enabled:
  123. raise AuthError(
  124. 403, "Account renewal via email is disabled on this server."
  125. )
  126. expiration_ts = await self.store.get_expiration_ts_for_user(user_id)
  127. # If this user isn't set to be expired, raise an error.
  128. if expiration_ts is None:
  129. raise SynapseError(400, "User has no expiration time: %s" % (user_id,))
  130. await self._send_renewal_email(user_id, expiration_ts)
  131. async def _send_renewal_email(self, user_id: str, expiration_ts: int) -> None:
  132. """Sends out a renewal email to every email address attached to the given user
  133. with a unique link allowing them to renew their account.
  134. Args:
  135. user_id: ID of the user to send email(s) to.
  136. expiration_ts: Timestamp in milliseconds for the expiration date of
  137. this user's account (used in the email templates).
  138. """
  139. addresses = await self._get_email_addresses_for_user(user_id)
  140. # Stop right here if the user doesn't have at least one email address.
  141. # In this case, they will have to ask their server admin to renew their
  142. # account manually.
  143. # We don't need to do a specific check to make sure the account isn't
  144. # deactivated, as a deactivated account isn't supposed to have any
  145. # email address attached to it.
  146. if not addresses:
  147. return
  148. try:
  149. user_display_name = await self.store.get_profile_displayname(
  150. UserID.from_string(user_id)
  151. )
  152. if user_display_name is None:
  153. user_display_name = user_id
  154. except StoreError:
  155. user_display_name = user_id
  156. renewal_token = await self._get_renewal_token(user_id)
  157. url = "%s_matrix/client/unstable/account_validity/renew?token=%s" % (
  158. self.hs.config.server.public_baseurl,
  159. renewal_token,
  160. )
  161. template_vars = {
  162. "display_name": user_display_name,
  163. "expiration_ts": expiration_ts,
  164. "url": url,
  165. }
  166. html_text = self._template_html.render(**template_vars)
  167. plain_text = self._template_text.render(**template_vars)
  168. for address in addresses:
  169. raw_to = email.utils.parseaddr(address)[1]
  170. await self.send_email_handler.send_email(
  171. email_address=raw_to,
  172. subject=self._renew_email_subject,
  173. app_name=self._app_name,
  174. html=html_text,
  175. text=plain_text,
  176. )
  177. await self.store.set_renewal_mail_status(user_id=user_id, email_sent=True)
  178. async def _get_email_addresses_for_user(self, user_id: str) -> List[str]:
  179. """Retrieve the list of email addresses attached to a user's account.
  180. Args:
  181. user_id: ID of the user to lookup email addresses for.
  182. Returns:
  183. Email addresses for this account.
  184. """
  185. threepids = await self.store.user_get_threepids(user_id)
  186. addresses = []
  187. for threepid in threepids:
  188. if threepid.medium == "email":
  189. addresses.append(threepid.address)
  190. return addresses
  191. async def _get_renewal_token(self, user_id: str) -> str:
  192. """Generates a 32-byte long random string that will be inserted into the
  193. user's renewal email's unique link, then saves it into the database.
  194. Args:
  195. user_id: ID of the user to generate a string for.
  196. Returns:
  197. The generated string.
  198. Raises:
  199. StoreError(500): Couldn't generate a unique string after 5 attempts.
  200. """
  201. attempts = 0
  202. while attempts < 5:
  203. try:
  204. renewal_token = stringutils.random_string(32)
  205. await self.store.set_renewal_token_for_user(user_id, renewal_token)
  206. return renewal_token
  207. except StoreError:
  208. attempts += 1
  209. raise StoreError(500, "Couldn't generate a unique string as refresh string.")
  210. async def renew_account(self, renewal_token: str) -> Tuple[bool, bool, int]:
  211. """Renews the account attached to a given renewal token by pushing back the
  212. expiration date by the current validity period in the server's configuration.
  213. If it turns out that the token is valid but has already been used, then the
  214. token is considered stale. A token is stale if the 'token_used_ts_ms' db column
  215. is non-null.
  216. This method exists to support handling the legacy account validity /renew
  217. endpoint. If a module implements the on_legacy_renew callback, then this process
  218. is delegated to the module instead.
  219. Args:
  220. renewal_token: Token sent with the renewal request.
  221. Returns:
  222. A tuple containing:
  223. * A bool representing whether the token is valid and unused.
  224. * A bool which is `True` if the token is valid, but stale.
  225. * An int representing the user's expiry timestamp as milliseconds since the
  226. epoch, or 0 if the token was invalid.
  227. """
  228. # If a module supports triggering a renew from here, do that, otherwise do the
  229. # legacy dance.
  230. if self._module_api_callbacks.on_legacy_renew_callback is not None:
  231. return await self._module_api_callbacks.on_legacy_renew_callback(
  232. renewal_token
  233. )
  234. try:
  235. (
  236. user_id,
  237. current_expiration_ts,
  238. token_used_ts,
  239. ) = await self.store.get_user_from_renewal_token(renewal_token)
  240. except StoreError:
  241. return False, False, 0
  242. # Check whether this token has already been used.
  243. if token_used_ts:
  244. logger.info(
  245. "User '%s' attempted to use previously used token '%s' to renew account",
  246. user_id,
  247. renewal_token,
  248. )
  249. return False, True, current_expiration_ts
  250. logger.debug("Renewing an account for user %s", user_id)
  251. # Renew the account. Pass the renewal_token here so that it is not cleared.
  252. # We want to keep the token around in case the user attempts to renew their
  253. # account with the same token twice (clicking the email link twice).
  254. #
  255. # In that case, the token will be accepted, but the account's expiration ts
  256. # will remain unchanged.
  257. new_expiration_ts = await self.renew_account_for_user(
  258. user_id, renewal_token=renewal_token
  259. )
  260. return True, False, new_expiration_ts
  261. async def renew_account_for_user(
  262. self,
  263. user_id: str,
  264. expiration_ts: Optional[int] = None,
  265. email_sent: bool = False,
  266. renewal_token: Optional[str] = None,
  267. ) -> int:
  268. """Renews the account attached to a given user by pushing back the
  269. expiration date by the current validity period in the server's
  270. configuration.
  271. Args:
  272. user_id: The ID of the user to renew.
  273. expiration_ts: New expiration date. Defaults to now + validity period.
  274. email_sent: Whether an email has been sent for this validity period.
  275. renewal_token: Token sent with the renewal request. The user's token
  276. will be cleared if this is None.
  277. Returns:
  278. New expiration date for this account, as a timestamp in
  279. milliseconds since epoch.
  280. """
  281. now = self.clock.time_msec()
  282. if expiration_ts is None:
  283. assert self._account_validity_period is not None
  284. expiration_ts = now + self._account_validity_period
  285. await self.store.set_account_validity_for_user(
  286. user_id=user_id,
  287. expiration_ts=expiration_ts,
  288. email_sent=email_sent,
  289. renewal_token=renewal_token,
  290. token_used_ts=now,
  291. )
  292. return expiration_ts