account_validity.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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, Awaitable, Callable, List, Optional, Tuple
  18. from twisted.web.http import Request
  19. from synapse.api.errors import AuthError, StoreError, SynapseError
  20. from synapse.metrics.background_process_metrics import wrap_as_background_process
  21. from synapse.types import UserID
  22. from synapse.util import stringutils
  23. if TYPE_CHECKING:
  24. from synapse.server import HomeServer
  25. logger = logging.getLogger(__name__)
  26. # Types for callbacks to be registered via the module api
  27. IS_USER_EXPIRED_CALLBACK = Callable[[str], Awaitable[Optional[bool]]]
  28. ON_USER_REGISTRATION_CALLBACK = Callable[[str], Awaitable]
  29. # Temporary hooks to allow for a transition from `/_matrix/client` endpoints
  30. # to `/_synapse/client/account_validity`. See `register_account_validity_callbacks`.
  31. ON_LEGACY_SEND_MAIL_CALLBACK = Callable[[str], Awaitable]
  32. ON_LEGACY_RENEW_CALLBACK = Callable[[str], Awaitable[Tuple[bool, bool, int]]]
  33. ON_LEGACY_ADMIN_REQUEST = Callable[[Request], Awaitable]
  34. class AccountValidityHandler:
  35. def __init__(self, hs: "HomeServer"):
  36. self.hs = hs
  37. self.config = hs.config
  38. self.store = self.hs.get_datastore()
  39. self.send_email_handler = self.hs.get_send_email_handler()
  40. self.clock = self.hs.get_clock()
  41. self._app_name = self.hs.config.email_app_name
  42. self._account_validity_enabled = (
  43. hs.config.account_validity.account_validity_enabled
  44. )
  45. self._account_validity_renew_by_email_enabled = (
  46. hs.config.account_validity.account_validity_renew_by_email_enabled
  47. )
  48. self._account_validity_period = None
  49. if self._account_validity_enabled:
  50. self._account_validity_period = (
  51. hs.config.account_validity.account_validity_period
  52. )
  53. if (
  54. self._account_validity_enabled
  55. and self._account_validity_renew_by_email_enabled
  56. ):
  57. # Don't do email-specific configuration if renewal by email is disabled.
  58. self._template_html = (
  59. hs.config.account_validity.account_validity_template_html
  60. )
  61. self._template_text = (
  62. hs.config.account_validity.account_validity_template_text
  63. )
  64. self._renew_email_subject = (
  65. hs.config.account_validity.account_validity_renew_email_subject
  66. )
  67. # Check the renewal emails to send and send them every 30min.
  68. if hs.config.worker.run_background_tasks:
  69. self.clock.looping_call(self._send_renewal_emails, 30 * 60 * 1000)
  70. self._is_user_expired_callbacks: List[IS_USER_EXPIRED_CALLBACK] = []
  71. self._on_user_registration_callbacks: List[ON_USER_REGISTRATION_CALLBACK] = []
  72. self._on_legacy_send_mail_callback: Optional[
  73. ON_LEGACY_SEND_MAIL_CALLBACK
  74. ] = None
  75. self._on_legacy_renew_callback: Optional[ON_LEGACY_RENEW_CALLBACK] = None
  76. # The legacy admin requests callback isn't a protected attribute because we need
  77. # to access it from the admin servlet, which is outside of this handler.
  78. self.on_legacy_admin_request_callback: Optional[ON_LEGACY_ADMIN_REQUEST] = None
  79. def register_account_validity_callbacks(
  80. self,
  81. is_user_expired: Optional[IS_USER_EXPIRED_CALLBACK] = None,
  82. on_user_registration: Optional[ON_USER_REGISTRATION_CALLBACK] = None,
  83. on_legacy_send_mail: Optional[ON_LEGACY_SEND_MAIL_CALLBACK] = None,
  84. on_legacy_renew: Optional[ON_LEGACY_RENEW_CALLBACK] = None,
  85. on_legacy_admin_request: Optional[ON_LEGACY_ADMIN_REQUEST] = None,
  86. ):
  87. """Register callbacks from module for each hook."""
  88. if is_user_expired is not None:
  89. self._is_user_expired_callbacks.append(is_user_expired)
  90. if on_user_registration is not None:
  91. self._on_user_registration_callbacks.append(on_user_registration)
  92. # The builtin account validity feature exposes 3 endpoints (send_mail, renew, and
  93. # an admin one). As part of moving the feature into a module, we need to change
  94. # the path from /_matrix/client/unstable/account_validity/... to
  95. # /_synapse/client/account_validity, because:
  96. #
  97. # * the feature isn't part of the Matrix spec thus shouldn't live under /_matrix
  98. # * the way we register servlets means that modules can't register resources
  99. # under /_matrix/client
  100. #
  101. # We need to allow for a transition period between the old and new endpoints
  102. # in order to allow for clients to update (and for emails to be processed).
  103. #
  104. # Once the email-account-validity module is loaded, it will take control of account
  105. # validity by moving the rows from our `account_validity` table into its own table.
  106. #
  107. # Therefore, we need to allow modules (in practice just the one implementing the
  108. # email-based account validity) to temporarily hook into the legacy endpoints so we
  109. # can route the traffic coming into the old endpoints into the module, which is
  110. # why we have the following three temporary hooks.
  111. if on_legacy_send_mail is not None:
  112. if self._on_legacy_send_mail_callback is not None:
  113. raise RuntimeError("Tried to register on_legacy_send_mail twice")
  114. self._on_legacy_send_mail_callback = on_legacy_send_mail
  115. if on_legacy_renew is not None:
  116. if self._on_legacy_renew_callback is not None:
  117. raise RuntimeError("Tried to register on_legacy_renew twice")
  118. self._on_legacy_renew_callback = on_legacy_renew
  119. if on_legacy_admin_request is not None:
  120. if self.on_legacy_admin_request_callback is not None:
  121. raise RuntimeError("Tried to register on_legacy_admin_request twice")
  122. self.on_legacy_admin_request_callback = on_legacy_admin_request
  123. async def is_user_expired(self, user_id: str) -> bool:
  124. """Checks if a user has expired against third-party modules.
  125. Args:
  126. user_id: The user to check the expiry of.
  127. Returns:
  128. Whether the user has expired.
  129. """
  130. for callback in self._is_user_expired_callbacks:
  131. expired = await callback(user_id)
  132. if expired is not None:
  133. return expired
  134. if self._account_validity_enabled:
  135. # If no module could determine whether the user has expired and the legacy
  136. # configuration is enabled, fall back to it.
  137. return await self.store.is_account_expired(user_id, self.clock.time_msec())
  138. return False
  139. async def on_user_registration(self, user_id: str):
  140. """Tell third-party modules about a user's registration.
  141. Args:
  142. user_id: The ID of the newly registered user.
  143. """
  144. for callback in self._on_user_registration_callbacks:
  145. await callback(user_id)
  146. @wrap_as_background_process("send_renewals")
  147. async def _send_renewal_emails(self) -> None:
  148. """Gets the list of users whose account is expiring in the amount of time
  149. configured in the ``renew_at`` parameter from the ``account_validity``
  150. configuration, and sends renewal emails to all of these users as long as they
  151. have an email 3PID attached to their account.
  152. """
  153. expiring_users = await self.store.get_users_expiring_soon()
  154. if expiring_users:
  155. for user in expiring_users:
  156. await self._send_renewal_email(
  157. user_id=user["user_id"], expiration_ts=user["expiration_ts_ms"]
  158. )
  159. async def send_renewal_email_to_user(self, user_id: str) -> None:
  160. """
  161. Send a renewal email for a specific user.
  162. Args:
  163. user_id: The user ID to send a renewal email for.
  164. Raises:
  165. SynapseError if the user is not set to renew.
  166. """
  167. # If a module supports sending a renewal email from here, do that, otherwise do
  168. # the legacy dance.
  169. if self._on_legacy_send_mail_callback is not None:
  170. await self._on_legacy_send_mail_callback(user_id)
  171. return
  172. if not self._account_validity_renew_by_email_enabled:
  173. raise AuthError(
  174. 403, "Account renewal via email is disabled on this server."
  175. )
  176. expiration_ts = await self.store.get_expiration_ts_for_user(user_id)
  177. # If this user isn't set to be expired, raise an error.
  178. if expiration_ts is None:
  179. raise SynapseError(400, "User has no expiration time: %s" % (user_id,))
  180. await self._send_renewal_email(user_id, expiration_ts)
  181. async def _send_renewal_email(self, user_id: str, expiration_ts: int) -> None:
  182. """Sends out a renewal email to every email address attached to the given user
  183. with a unique link allowing them to renew their account.
  184. Args:
  185. user_id: ID of the user to send email(s) to.
  186. expiration_ts: Timestamp in milliseconds for the expiration date of
  187. this user's account (used in the email templates).
  188. """
  189. addresses = await self._get_email_addresses_for_user(user_id)
  190. # Stop right here if the user doesn't have at least one email address.
  191. # In this case, they will have to ask their server admin to renew their
  192. # account manually.
  193. # We don't need to do a specific check to make sure the account isn't
  194. # deactivated, as a deactivated account isn't supposed to have any
  195. # email address attached to it.
  196. if not addresses:
  197. return
  198. try:
  199. user_display_name = await self.store.get_profile_displayname(
  200. UserID.from_string(user_id).localpart
  201. )
  202. if user_display_name is None:
  203. user_display_name = user_id
  204. except StoreError:
  205. user_display_name = user_id
  206. renewal_token = await self._get_renewal_token(user_id)
  207. url = "%s_matrix/client/unstable/account_validity/renew?token=%s" % (
  208. self.hs.config.server.public_baseurl,
  209. renewal_token,
  210. )
  211. template_vars = {
  212. "display_name": user_display_name,
  213. "expiration_ts": expiration_ts,
  214. "url": url,
  215. }
  216. html_text = self._template_html.render(**template_vars)
  217. plain_text = self._template_text.render(**template_vars)
  218. for address in addresses:
  219. raw_to = email.utils.parseaddr(address)[1]
  220. await self.send_email_handler.send_email(
  221. email_address=raw_to,
  222. subject=self._renew_email_subject,
  223. app_name=self._app_name,
  224. html=html_text,
  225. text=plain_text,
  226. )
  227. await self.store.set_renewal_mail_status(user_id=user_id, email_sent=True)
  228. async def _get_email_addresses_for_user(self, user_id: str) -> List[str]:
  229. """Retrieve the list of email addresses attached to a user's account.
  230. Args:
  231. user_id: ID of the user to lookup email addresses for.
  232. Returns:
  233. Email addresses for this account.
  234. """
  235. threepids = await self.store.user_get_threepids(user_id)
  236. addresses = []
  237. for threepid in threepids:
  238. if threepid["medium"] == "email":
  239. addresses.append(threepid["address"])
  240. return addresses
  241. async def _get_renewal_token(self, user_id: str) -> str:
  242. """Generates a 32-byte long random string that will be inserted into the
  243. user's renewal email's unique link, then saves it into the database.
  244. Args:
  245. user_id: ID of the user to generate a string for.
  246. Returns:
  247. The generated string.
  248. Raises:
  249. StoreError(500): Couldn't generate a unique string after 5 attempts.
  250. """
  251. attempts = 0
  252. while attempts < 5:
  253. try:
  254. renewal_token = stringutils.random_string(32)
  255. await self.store.set_renewal_token_for_user(user_id, renewal_token)
  256. return renewal_token
  257. except StoreError:
  258. attempts += 1
  259. raise StoreError(500, "Couldn't generate a unique string as refresh string.")
  260. async def renew_account(self, renewal_token: str) -> Tuple[bool, bool, int]:
  261. """Renews the account attached to a given renewal token by pushing back the
  262. expiration date by the current validity period in the server's configuration.
  263. If it turns out that the token is valid but has already been used, then the
  264. token is considered stale. A token is stale if the 'token_used_ts_ms' db column
  265. is non-null.
  266. This method exists to support handling the legacy account validity /renew
  267. endpoint. If a module implements the on_legacy_renew callback, then this process
  268. is delegated to the module instead.
  269. Args:
  270. renewal_token: Token sent with the renewal request.
  271. Returns:
  272. A tuple containing:
  273. * A bool representing whether the token is valid and unused.
  274. * A bool which is `True` if the token is valid, but stale.
  275. * An int representing the user's expiry timestamp as milliseconds since the
  276. epoch, or 0 if the token was invalid.
  277. """
  278. # If a module supports triggering a renew from here, do that, otherwise do the
  279. # legacy dance.
  280. if self._on_legacy_renew_callback is not None:
  281. return await self._on_legacy_renew_callback(renewal_token)
  282. try:
  283. (
  284. user_id,
  285. current_expiration_ts,
  286. token_used_ts,
  287. ) = await self.store.get_user_from_renewal_token(renewal_token)
  288. except StoreError:
  289. return False, False, 0
  290. # Check whether this token has already been used.
  291. if token_used_ts:
  292. logger.info(
  293. "User '%s' attempted to use previously used token '%s' to renew account",
  294. user_id,
  295. renewal_token,
  296. )
  297. return False, True, current_expiration_ts
  298. logger.debug("Renewing an account for user %s", user_id)
  299. # Renew the account. Pass the renewal_token here so that it is not cleared.
  300. # We want to keep the token around in case the user attempts to renew their
  301. # account with the same token twice (clicking the email link twice).
  302. #
  303. # In that case, the token will be accepted, but the account's expiration ts
  304. # will remain unchanged.
  305. new_expiration_ts = await self.renew_account_for_user(
  306. user_id, renewal_token=renewal_token
  307. )
  308. return True, False, new_expiration_ts
  309. async def renew_account_for_user(
  310. self,
  311. user_id: str,
  312. expiration_ts: Optional[int] = None,
  313. email_sent: bool = False,
  314. renewal_token: Optional[str] = None,
  315. ) -> int:
  316. """Renews the account attached to a given user by pushing back the
  317. expiration date by the current validity period in the server's
  318. configuration.
  319. Args:
  320. user_id: The ID of the user to renew.
  321. expiration_ts: New expiration date. Defaults to now + validity period.
  322. email_sent: Whether an email has been sent for this validity period.
  323. renewal_token: Token sent with the renewal request. The user's token
  324. will be cleared if this is None.
  325. Returns:
  326. New expiration date for this account, as a timestamp in
  327. milliseconds since epoch.
  328. """
  329. now = self.clock.time_msec()
  330. if expiration_ts is None:
  331. assert self._account_validity_period is not None
  332. expiration_ts = now + self._account_validity_period
  333. await self.store.set_account_validity_for_user(
  334. user_id=user_id,
  335. expiration_ts=expiration_ts,
  336. email_sent=email_sent,
  337. renewal_token=renewal_token,
  338. token_used_ts=now,
  339. )
  340. return expiration_ts