2019-04-10 18:58:47 +02:00
|
|
|
# Copyright 2019 New Vector Ltd
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
import email.mime.multipart
|
|
|
|
import email.utils
|
|
|
|
import logging
|
2023-03-16 11:35:31 +01:00
|
|
|
from typing import TYPE_CHECKING, List, Optional, Tuple
|
2021-07-16 18:11:53 +02:00
|
|
|
|
|
|
|
from synapse.api.errors import AuthError, StoreError, SynapseError
|
2020-10-20 17:29:38 +02:00
|
|
|
from synapse.metrics.background_process_metrics import wrap_as_background_process
|
2019-04-10 18:58:47 +02:00
|
|
|
from synapse.types import UserID
|
|
|
|
from synapse.util import stringutils
|
2022-05-09 13:31:14 +02:00
|
|
|
from synapse.util.async_helpers import delay_cancellation
|
2019-04-10 18:58:47 +02:00
|
|
|
|
2020-10-26 19:17:31 +01:00
|
|
|
if TYPE_CHECKING:
|
2021-03-23 12:12:48 +01:00
|
|
|
from synapse.server import HomeServer
|
2020-10-26 19:17:31 +01:00
|
|
|
|
2019-04-10 18:58:47 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2020-09-04 12:54:56 +02:00
|
|
|
class AccountValidityHandler:
|
2020-10-26 19:17:31 +01:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2019-04-10 18:58:47 +02:00
|
|
|
self.hs = hs
|
2019-09-06 12:35:28 +02:00
|
|
|
self.config = hs.config
|
2023-03-16 11:35:31 +01:00
|
|
|
self.store = hs.get_datastores().main
|
|
|
|
self.send_email_handler = hs.get_send_email_handler()
|
|
|
|
self.clock = hs.get_clock()
|
2019-04-10 18:58:47 +02:00
|
|
|
|
2023-03-16 11:35:31 +01:00
|
|
|
self._app_name = hs.config.email.email_app_name
|
|
|
|
self._module_api_callbacks = hs.get_module_api_callbacks().account_validity
|
2021-05-17 12:33:38 +02:00
|
|
|
|
2021-04-19 20:16:34 +02:00
|
|
|
self._account_validity_enabled = (
|
|
|
|
hs.config.account_validity.account_validity_enabled
|
|
|
|
)
|
|
|
|
self._account_validity_renew_by_email_enabled = (
|
|
|
|
hs.config.account_validity.account_validity_renew_by_email_enabled
|
|
|
|
)
|
|
|
|
|
|
|
|
self._account_validity_period = None
|
|
|
|
if self._account_validity_enabled:
|
|
|
|
self._account_validity_period = (
|
|
|
|
hs.config.account_validity.account_validity_period
|
|
|
|
)
|
2019-04-10 18:58:47 +02:00
|
|
|
|
2020-03-16 13:16:30 +01:00
|
|
|
if (
|
2021-04-19 20:16:34 +02:00
|
|
|
self._account_validity_enabled
|
|
|
|
and self._account_validity_renew_by_email_enabled
|
2020-03-16 13:16:30 +01:00
|
|
|
):
|
2019-04-10 18:58:47 +02:00
|
|
|
# Don't do email-specific configuration if renewal by email is disabled.
|
2021-10-06 16:47:41 +02:00
|
|
|
self._template_html = hs.config.email.account_validity_template_html
|
|
|
|
self._template_text = hs.config.email.account_validity_template_text
|
2021-05-17 12:33:38 +02:00
|
|
|
self._renew_email_subject = (
|
2021-04-19 20:16:34 +02:00
|
|
|
hs.config.account_validity.account_validity_renew_email_subject
|
|
|
|
)
|
2020-08-17 18:05:00 +02:00
|
|
|
|
2019-04-10 18:58:47 +02:00
|
|
|
# Check the renewal emails to send and send them every 30min.
|
2021-09-13 19:07:12 +02:00
|
|
|
if hs.config.worker.run_background_tasks:
|
2020-10-20 17:29:38 +02:00
|
|
|
self.clock.looping_call(self._send_renewal_emails, 30 * 60 * 1000)
|
2019-04-10 18:58:47 +02:00
|
|
|
|
2021-07-16 18:11:53 +02:00
|
|
|
async def is_user_expired(self, user_id: str) -> bool:
|
|
|
|
"""Checks if a user has expired against third-party modules.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
user_id: The user to check the expiry of.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Whether the user has expired.
|
|
|
|
"""
|
2023-03-16 11:35:31 +01:00
|
|
|
for callback in self._module_api_callbacks.is_user_expired_callbacks:
|
2022-05-09 13:31:14 +02:00
|
|
|
expired = await delay_cancellation(callback(user_id))
|
2021-07-16 18:11:53 +02:00
|
|
|
if expired is not None:
|
|
|
|
return expired
|
|
|
|
|
|
|
|
if self._account_validity_enabled:
|
|
|
|
# If no module could determine whether the user has expired and the legacy
|
|
|
|
# configuration is enabled, fall back to it.
|
|
|
|
return await self.store.is_account_expired(user_id, self.clock.time_msec())
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2021-09-20 14:56:23 +02:00
|
|
|
async def on_user_registration(self, user_id: str) -> None:
|
2021-07-16 18:11:53 +02:00
|
|
|
"""Tell third-party modules about a user's registration.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
user_id: The ID of the newly registered user.
|
|
|
|
"""
|
2023-03-16 11:35:31 +01:00
|
|
|
for callback in self._module_api_callbacks.on_user_registration_callbacks:
|
2021-07-16 18:11:53 +02:00
|
|
|
await callback(user_id)
|
|
|
|
|
2020-10-20 17:29:38 +02:00
|
|
|
@wrap_as_background_process("send_renewals")
|
2020-10-26 19:17:31 +01:00
|
|
|
async def _send_renewal_emails(self) -> None:
|
2019-04-10 18:58:47 +02:00
|
|
|
"""Gets the list of users whose account is expiring in the amount of time
|
|
|
|
configured in the ``renew_at`` parameter from the ``account_validity``
|
|
|
|
configuration, and sends renewal emails to all of these users as long as they
|
|
|
|
have an email 3PID attached to their account.
|
|
|
|
"""
|
2019-12-10 12:13:15 +01:00
|
|
|
expiring_users = await self.store.get_users_expiring_soon()
|
2019-04-10 18:58:47 +02:00
|
|
|
|
|
|
|
if expiring_users:
|
2022-04-12 12:54:00 +02:00
|
|
|
for user_id, expiration_ts_ms in expiring_users:
|
2019-12-10 12:13:15 +01:00
|
|
|
await self._send_renewal_email(
|
2022-04-12 12:54:00 +02:00
|
|
|
user_id=user_id, expiration_ts=expiration_ts_ms
|
2019-04-10 18:58:47 +02:00
|
|
|
)
|
|
|
|
|
2020-10-26 19:17:31 +01:00
|
|
|
async def send_renewal_email_to_user(self, user_id: str) -> None:
|
|
|
|
"""
|
|
|
|
Send a renewal email for a specific user.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
user_id: The user ID to send a renewal email for.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
SynapseError if the user is not set to renew.
|
|
|
|
"""
|
2021-07-16 18:11:53 +02:00
|
|
|
# If a module supports sending a renewal email from here, do that, otherwise do
|
|
|
|
# the legacy dance.
|
2023-03-16 11:35:31 +01:00
|
|
|
if self._module_api_callbacks.on_legacy_send_mail_callback is not None:
|
|
|
|
await self._module_api_callbacks.on_legacy_send_mail_callback(user_id)
|
2021-07-16 18:11:53 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
if not self._account_validity_renew_by_email_enabled:
|
|
|
|
raise AuthError(
|
|
|
|
403, "Account renewal via email is disabled on this server."
|
|
|
|
)
|
|
|
|
|
2019-12-10 12:13:15 +01:00
|
|
|
expiration_ts = await self.store.get_expiration_ts_for_user(user_id)
|
2020-10-26 19:17:31 +01:00
|
|
|
|
|
|
|
# If this user isn't set to be expired, raise an error.
|
|
|
|
if expiration_ts is None:
|
|
|
|
raise SynapseError(400, "User has no expiration time: %s" % (user_id,))
|
|
|
|
|
2019-12-10 12:13:15 +01:00
|
|
|
await self._send_renewal_email(user_id, expiration_ts)
|
2019-04-16 21:13:59 +02:00
|
|
|
|
2020-10-26 19:17:31 +01:00
|
|
|
async def _send_renewal_email(self, user_id: str, expiration_ts: int) -> None:
|
2019-04-10 18:58:47 +02:00
|
|
|
"""Sends out a renewal email to every email address attached to the given user
|
|
|
|
with a unique link allowing them to renew their account.
|
|
|
|
|
|
|
|
Args:
|
2019-12-10 12:13:15 +01:00
|
|
|
user_id: ID of the user to send email(s) to.
|
|
|
|
expiration_ts: Timestamp in milliseconds for the expiration date of
|
2019-04-10 18:58:47 +02:00
|
|
|
this user's account (used in the email templates).
|
|
|
|
"""
|
2019-12-10 12:13:15 +01:00
|
|
|
addresses = await self._get_email_addresses_for_user(user_id)
|
2019-04-10 18:58:47 +02:00
|
|
|
|
|
|
|
# Stop right here if the user doesn't have at least one email address.
|
|
|
|
# In this case, they will have to ask their server admin to renew their
|
|
|
|
# account manually.
|
2019-06-07 16:30:54 +02:00
|
|
|
# We don't need to do a specific check to make sure the account isn't
|
|
|
|
# deactivated, as a deactivated account isn't supposed to have any
|
|
|
|
# email address attached to it.
|
2019-04-10 18:58:47 +02:00
|
|
|
if not addresses:
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
2019-12-10 12:13:15 +01:00
|
|
|
user_display_name = await self.store.get_profile_displayname(
|
2023-06-03 02:24:13 +02:00
|
|
|
UserID.from_string(user_id)
|
2019-04-10 18:58:47 +02:00
|
|
|
)
|
|
|
|
if user_display_name is None:
|
|
|
|
user_display_name = user_id
|
|
|
|
except StoreError:
|
|
|
|
user_display_name = user_id
|
|
|
|
|
2019-12-10 12:13:15 +01:00
|
|
|
renewal_token = await self._get_renewal_token(user_id)
|
2019-04-10 18:58:47 +02:00
|
|
|
url = "%s_matrix/client/unstable/account_validity/renew?token=%s" % (
|
2021-09-13 19:07:12 +02:00
|
|
|
self.hs.config.server.public_baseurl,
|
2019-04-10 18:58:47 +02:00
|
|
|
renewal_token,
|
|
|
|
)
|
|
|
|
|
|
|
|
template_vars = {
|
|
|
|
"display_name": user_display_name,
|
|
|
|
"expiration_ts": expiration_ts,
|
|
|
|
"url": url,
|
|
|
|
}
|
|
|
|
|
|
|
|
html_text = self._template_html.render(**template_vars)
|
|
|
|
plain_text = self._template_text.render(**template_vars)
|
|
|
|
|
|
|
|
for address in addresses:
|
|
|
|
raw_to = email.utils.parseaddr(address)[1]
|
|
|
|
|
2021-05-17 12:33:38 +02:00
|
|
|
await self.send_email_handler.send_email(
|
|
|
|
email_address=raw_to,
|
|
|
|
subject=self._renew_email_subject,
|
|
|
|
app_name=self._app_name,
|
|
|
|
html=html_text,
|
|
|
|
text=plain_text,
|
2019-06-20 11:32:02 +02:00
|
|
|
)
|
|
|
|
|
2019-12-10 12:13:15 +01:00
|
|
|
await self.store.set_renewal_mail_status(user_id=user_id, email_sent=True)
|
2019-04-10 18:58:47 +02:00
|
|
|
|
2019-12-10 12:13:15 +01:00
|
|
|
async def _get_email_addresses_for_user(self, user_id: str) -> List[str]:
|
2019-04-10 18:58:47 +02:00
|
|
|
"""Retrieve the list of email addresses attached to a user's account.
|
|
|
|
|
|
|
|
Args:
|
2019-12-10 12:13:15 +01:00
|
|
|
user_id: ID of the user to lookup email addresses for.
|
2019-04-10 18:58:47 +02:00
|
|
|
|
|
|
|
Returns:
|
2019-12-10 12:13:15 +01:00
|
|
|
Email addresses for this account.
|
2019-04-10 18:58:47 +02:00
|
|
|
"""
|
2019-12-10 12:13:15 +01:00
|
|
|
threepids = await self.store.user_get_threepids(user_id)
|
2019-04-10 18:58:47 +02:00
|
|
|
|
|
|
|
addresses = []
|
|
|
|
for threepid in threepids:
|
2023-10-12 02:08:11 +02:00
|
|
|
if threepid.medium == "email":
|
|
|
|
addresses.append(threepid.address)
|
2019-04-10 18:58:47 +02:00
|
|
|
|
2019-07-23 15:00:55 +02:00
|
|
|
return addresses
|
2019-04-10 18:58:47 +02:00
|
|
|
|
2019-12-10 12:13:15 +01:00
|
|
|
async def _get_renewal_token(self, user_id: str) -> str:
|
2019-04-10 18:58:47 +02:00
|
|
|
"""Generates a 32-byte long random string that will be inserted into the
|
|
|
|
user's renewal email's unique link, then saves it into the database.
|
|
|
|
|
|
|
|
Args:
|
2019-12-10 12:13:15 +01:00
|
|
|
user_id: ID of the user to generate a string for.
|
2019-04-10 18:58:47 +02:00
|
|
|
|
|
|
|
Returns:
|
2019-12-10 12:13:15 +01:00
|
|
|
The generated string.
|
2019-04-10 18:58:47 +02:00
|
|
|
|
|
|
|
Raises:
|
|
|
|
StoreError(500): Couldn't generate a unique string after 5 attempts.
|
|
|
|
"""
|
|
|
|
attempts = 0
|
|
|
|
while attempts < 5:
|
|
|
|
try:
|
|
|
|
renewal_token = stringutils.random_string(32)
|
2019-12-10 12:13:15 +01:00
|
|
|
await self.store.set_renewal_token_for_user(user_id, renewal_token)
|
2019-07-23 15:00:55 +02:00
|
|
|
return renewal_token
|
2019-04-10 18:58:47 +02:00
|
|
|
except StoreError:
|
|
|
|
attempts += 1
|
|
|
|
raise StoreError(500, "Couldn't generate a unique string as refresh string.")
|
|
|
|
|
2021-04-19 20:16:34 +02:00
|
|
|
async def renew_account(self, renewal_token: str) -> Tuple[bool, bool, int]:
|
2019-04-10 18:58:47 +02:00
|
|
|
"""Renews the account attached to a given renewal token by pushing back the
|
|
|
|
expiration date by the current validity period in the server's configuration.
|
|
|
|
|
2021-04-19 20:16:34 +02:00
|
|
|
If it turns out that the token is valid but has already been used, then the
|
|
|
|
token is considered stale. A token is stale if the 'token_used_ts_ms' db column
|
|
|
|
is non-null.
|
|
|
|
|
2021-07-16 18:11:53 +02:00
|
|
|
This method exists to support handling the legacy account validity /renew
|
|
|
|
endpoint. If a module implements the on_legacy_renew callback, then this process
|
|
|
|
is delegated to the module instead.
|
|
|
|
|
2019-04-10 18:58:47 +02:00
|
|
|
Args:
|
2019-12-10 12:13:15 +01:00
|
|
|
renewal_token: Token sent with the renewal request.
|
2019-07-31 18:12:04 +02:00
|
|
|
Returns:
|
2021-04-19 20:16:34 +02:00
|
|
|
A tuple containing:
|
|
|
|
* A bool representing whether the token is valid and unused.
|
|
|
|
* A bool which is `True` if the token is valid, but stale.
|
|
|
|
* An int representing the user's expiry timestamp as milliseconds since the
|
|
|
|
epoch, or 0 if the token was invalid.
|
2019-04-10 18:58:47 +02:00
|
|
|
"""
|
2021-07-16 18:11:53 +02:00
|
|
|
# If a module supports triggering a renew from here, do that, otherwise do the
|
|
|
|
# legacy dance.
|
2023-03-16 11:35:31 +01:00
|
|
|
if self._module_api_callbacks.on_legacy_renew_callback is not None:
|
|
|
|
return await self._module_api_callbacks.on_legacy_renew_callback(
|
|
|
|
renewal_token
|
|
|
|
)
|
2021-07-16 18:11:53 +02:00
|
|
|
|
2019-07-31 18:12:04 +02:00
|
|
|
try:
|
2021-04-19 20:16:34 +02:00
|
|
|
(
|
|
|
|
user_id,
|
|
|
|
current_expiration_ts,
|
|
|
|
token_used_ts,
|
|
|
|
) = await self.store.get_user_from_renewal_token(renewal_token)
|
2019-07-31 18:12:04 +02:00
|
|
|
except StoreError:
|
2021-04-19 20:16:34 +02:00
|
|
|
return False, False, 0
|
|
|
|
|
|
|
|
# Check whether this token has already been used.
|
|
|
|
if token_used_ts:
|
|
|
|
logger.info(
|
|
|
|
"User '%s' attempted to use previously used token '%s' to renew account",
|
|
|
|
user_id,
|
|
|
|
renewal_token,
|
|
|
|
)
|
|
|
|
return False, True, current_expiration_ts
|
2019-07-31 18:12:04 +02:00
|
|
|
|
2019-04-10 18:58:47 +02:00
|
|
|
logger.debug("Renewing an account for user %s", user_id)
|
|
|
|
|
2021-04-19 20:16:34 +02:00
|
|
|
# Renew the account. Pass the renewal_token here so that it is not cleared.
|
|
|
|
# We want to keep the token around in case the user attempts to renew their
|
|
|
|
# account with the same token twice (clicking the email link twice).
|
|
|
|
#
|
|
|
|
# In that case, the token will be accepted, but the account's expiration ts
|
|
|
|
# will remain unchanged.
|
|
|
|
new_expiration_ts = await self.renew_account_for_user(
|
|
|
|
user_id, renewal_token=renewal_token
|
|
|
|
)
|
|
|
|
|
|
|
|
return True, False, new_expiration_ts
|
2019-07-31 18:12:04 +02:00
|
|
|
|
2019-12-10 12:13:15 +01:00
|
|
|
async def renew_account_for_user(
|
2021-04-05 15:10:18 +02:00
|
|
|
self,
|
|
|
|
user_id: str,
|
|
|
|
expiration_ts: Optional[int] = None,
|
|
|
|
email_sent: bool = False,
|
2021-04-19 20:16:34 +02:00
|
|
|
renewal_token: Optional[str] = None,
|
2019-12-10 12:13:15 +01:00
|
|
|
) -> int:
|
2019-04-16 21:13:59 +02:00
|
|
|
"""Renews the account attached to a given user by pushing back the
|
|
|
|
expiration date by the current validity period in the server's
|
|
|
|
configuration.
|
2019-04-10 18:58:47 +02:00
|
|
|
|
2019-04-16 21:13:59 +02:00
|
|
|
Args:
|
2021-04-19 20:16:34 +02:00
|
|
|
user_id: The ID of the user to renew.
|
2019-12-10 12:13:15 +01:00
|
|
|
expiration_ts: New expiration date. Defaults to now + validity period.
|
2021-04-19 20:16:34 +02:00
|
|
|
email_sent: Whether an email has been sent for this validity period.
|
|
|
|
renewal_token: Token sent with the renewal request. The user's token
|
|
|
|
will be cleared if this is None.
|
2019-04-16 21:13:59 +02:00
|
|
|
|
|
|
|
Returns:
|
2019-12-10 12:13:15 +01:00
|
|
|
New expiration date for this account, as a timestamp in
|
|
|
|
milliseconds since epoch.
|
2019-04-16 21:13:59 +02:00
|
|
|
"""
|
2021-04-19 20:16:34 +02:00
|
|
|
now = self.clock.time_msec()
|
2019-04-16 21:13:59 +02:00
|
|
|
if expiration_ts is None:
|
2021-09-10 18:03:18 +02:00
|
|
|
assert self._account_validity_period is not None
|
2021-04-19 20:16:34 +02:00
|
|
|
expiration_ts = now + self._account_validity_period
|
2019-04-16 21:13:59 +02:00
|
|
|
|
2019-12-10 12:13:15 +01:00
|
|
|
await self.store.set_account_validity_for_user(
|
2021-04-19 20:16:34 +02:00
|
|
|
user_id=user_id,
|
|
|
|
expiration_ts=expiration_ts,
|
|
|
|
email_sent=email_sent,
|
|
|
|
renewal_token=renewal_token,
|
|
|
|
token_used_ts=now,
|
2019-04-10 18:58:47 +02:00
|
|
|
)
|
2019-04-16 21:13:59 +02:00
|
|
|
|
2019-07-23 15:00:55 +02:00
|
|
|
return expiration_ts
|