You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

349 line
15 KiB

  1. # Copyright 2015-2016 OpenMarket Ltd
  2. # Copyright 2017-2018 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # This file can't be called email.py because if it is, we cannot:
  17. import email.utils
  18. import logging
  19. import os
  20. from typing import Any
  21. import attr
  22. from synapse.types import JsonDict
  23. from ._base import Config, ConfigError
  24. logger = logging.getLogger(__name__)
  25. MISSING_PASSWORD_RESET_CONFIG_ERROR = """\
  26. Password reset emails are enabled on this homeserver due to a partial
  27. 'email' block. However, the following required keys are missing:
  28. %s
  29. """
  30. DEFAULT_SUBJECTS = {
  31. "message_from_person_in_room": "[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...",
  32. "message_from_person": "[%(app)s] You have a message on %(app)s from %(person)s...",
  33. "messages_from_person": "[%(app)s] You have messages on %(app)s from %(person)s...",
  34. "messages_in_room": "[%(app)s] You have messages on %(app)s in the %(room)s room...",
  35. "messages_in_room_and_others": "[%(app)s] You have messages on %(app)s in the %(room)s room and others...",
  36. "messages_from_person_and_others": "[%(app)s] You have messages on %(app)s from %(person)s and others...",
  37. "invite_from_person": "[%(app)s] %(person)s has invited you to chat on %(app)s...",
  38. "invite_from_person_to_room": "[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...",
  39. "invite_from_person_to_space": "[%(app)s] %(person)s has invited you to join the %(space)s space on %(app)s...",
  40. "password_reset": "[%(server_name)s] Password reset",
  41. "email_validation": "[%(server_name)s] Validate your email",
  42. }
  43. LEGACY_TEMPLATE_DIR_WARNING = """
  44. This server's configuration file is using the deprecated 'template_dir' setting in the
  45. 'email' section. Support for this setting has been deprecated and will be removed in a
  46. future version of Synapse. Server admins should instead use the new
  47. 'custom_template_directory' setting documented here:
  48. https://matrix-org.github.io/synapse/latest/templates.html
  49. ---------------------------------------------------------------------------------------"""
  50. @attr.s(slots=True, frozen=True, auto_attribs=True)
  51. class EmailSubjectConfig:
  52. message_from_person_in_room: str
  53. message_from_person: str
  54. messages_from_person: str
  55. messages_in_room: str
  56. messages_in_room_and_others: str
  57. messages_from_person_and_others: str
  58. invite_from_person: str
  59. invite_from_person_to_room: str
  60. invite_from_person_to_space: str
  61. password_reset: str
  62. email_validation: str
  63. class EmailConfig(Config):
  64. section = "email"
  65. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  66. # TODO: We should separate better the email configuration from the notification
  67. # and account validity config.
  68. self.email_enable_notifs = False
  69. email_config = config.get("email")
  70. if email_config is None:
  71. email_config = {}
  72. self.force_tls = email_config.get("force_tls", False)
  73. self.email_smtp_host = email_config.get("smtp_host", "localhost")
  74. self.email_smtp_port = email_config.get(
  75. "smtp_port", 465 if self.force_tls else 25
  76. )
  77. self.email_smtp_user = email_config.get("smtp_user", None)
  78. self.email_smtp_pass = email_config.get("smtp_pass", None)
  79. self.require_transport_security = email_config.get(
  80. "require_transport_security", False
  81. )
  82. self.enable_smtp_tls = email_config.get("enable_tls", True)
  83. if self.force_tls and not self.enable_smtp_tls:
  84. raise ConfigError("email.force_tls requires email.enable_tls to be true")
  85. if self.require_transport_security and not self.enable_smtp_tls:
  86. raise ConfigError(
  87. "email.require_transport_security requires email.enable_tls to be true"
  88. )
  89. if "app_name" in email_config:
  90. self.email_app_name = email_config["app_name"]
  91. else:
  92. self.email_app_name = "Matrix"
  93. # TODO: Rename notif_from to something more generic, or have a separate
  94. # from for password resets, message notifications, etc?
  95. # Currently the email section is a bit bogged down with settings for
  96. # multiple functions. Would be good to split it out into separate
  97. # sections and only put the common ones under email:
  98. self.email_notif_from = email_config.get("notif_from", None)
  99. if self.email_notif_from is not None:
  100. # make sure it's valid
  101. parsed = email.utils.parseaddr(self.email_notif_from)
  102. if parsed[1] == "":
  103. raise RuntimeError("Invalid notif_from address")
  104. # A user-configurable template directory
  105. template_dir = email_config.get("template_dir")
  106. if template_dir is not None:
  107. logger.warning(LEGACY_TEMPLATE_DIR_WARNING)
  108. if isinstance(template_dir, str):
  109. # We need an absolute path, because we change directory after starting (and
  110. # we don't yet know what auxiliary templates like mail.css we will need).
  111. template_dir = os.path.abspath(template_dir)
  112. elif template_dir is not None:
  113. # If template_dir is something other than a str or None, warn the user
  114. raise ConfigError("Config option email.template_dir must be type str")
  115. self.email_enable_notifs = email_config.get("enable_notifs", False)
  116. if config.get("trust_identity_server_for_password_resets"):
  117. raise ConfigError(
  118. 'The config option "trust_identity_server_for_password_resets" '
  119. "is no longer supported. Please remove it from the config file."
  120. )
  121. # If we have email config settings, assume that we can verify ownership of
  122. # email addresses.
  123. self.can_verify_email = email_config != {}
  124. # Get lifetime of a validation token in milliseconds
  125. self.email_validation_token_lifetime = self.parse_duration(
  126. email_config.get("validation_token_lifetime", "1h")
  127. )
  128. if self.can_verify_email:
  129. missing = []
  130. if not self.email_notif_from:
  131. missing.append("email.notif_from")
  132. if missing:
  133. raise ConfigError(
  134. MISSING_PASSWORD_RESET_CONFIG_ERROR % (", ".join(missing),)
  135. )
  136. # These email templates have placeholders in them, and thus must be
  137. # parsed using a templating engine during a request
  138. password_reset_template_html = email_config.get(
  139. "password_reset_template_html", "password_reset.html"
  140. )
  141. password_reset_template_text = email_config.get(
  142. "password_reset_template_text", "password_reset.txt"
  143. )
  144. registration_template_html = email_config.get(
  145. "registration_template_html", "registration.html"
  146. )
  147. registration_template_text = email_config.get(
  148. "registration_template_text", "registration.txt"
  149. )
  150. add_threepid_template_html = email_config.get(
  151. "add_threepid_template_html", "add_threepid.html"
  152. )
  153. add_threepid_template_text = email_config.get(
  154. "add_threepid_template_text", "add_threepid.txt"
  155. )
  156. password_reset_template_failure_html = email_config.get(
  157. "password_reset_template_failure_html", "password_reset_failure.html"
  158. )
  159. registration_template_failure_html = email_config.get(
  160. "registration_template_failure_html", "registration_failure.html"
  161. )
  162. add_threepid_template_failure_html = email_config.get(
  163. "add_threepid_template_failure_html", "add_threepid_failure.html"
  164. )
  165. # These templates do not support any placeholder variables, so we
  166. # will read them from disk once during setup
  167. password_reset_template_success_html = email_config.get(
  168. "password_reset_template_success_html", "password_reset_success.html"
  169. )
  170. registration_template_success_html = email_config.get(
  171. "registration_template_success_html", "registration_success.html"
  172. )
  173. add_threepid_template_success_html = email_config.get(
  174. "add_threepid_template_success_html", "add_threepid_success.html"
  175. )
  176. # Read all templates from disk
  177. (
  178. self.email_password_reset_template_html,
  179. self.email_password_reset_template_text,
  180. self.email_registration_template_html,
  181. self.email_registration_template_text,
  182. self.email_add_threepid_template_html,
  183. self.email_add_threepid_template_text,
  184. self.email_password_reset_template_confirmation_html,
  185. self.email_password_reset_template_failure_html,
  186. self.email_registration_template_failure_html,
  187. self.email_add_threepid_template_failure_html,
  188. password_reset_template_success_html_template,
  189. registration_template_success_html_template,
  190. add_threepid_template_success_html_template,
  191. ) = self.read_templates(
  192. [
  193. password_reset_template_html,
  194. password_reset_template_text,
  195. registration_template_html,
  196. registration_template_text,
  197. add_threepid_template_html,
  198. add_threepid_template_text,
  199. "password_reset_confirmation.html",
  200. password_reset_template_failure_html,
  201. registration_template_failure_html,
  202. add_threepid_template_failure_html,
  203. password_reset_template_success_html,
  204. registration_template_success_html,
  205. add_threepid_template_success_html,
  206. ],
  207. (
  208. td
  209. for td in (
  210. self.root.server.custom_template_directory,
  211. template_dir,
  212. )
  213. if td
  214. ), # Filter out template_dir if not provided
  215. )
  216. # Render templates that do not contain any placeholders
  217. self.email_password_reset_template_success_html_content = (
  218. password_reset_template_success_html_template.render()
  219. )
  220. self.email_registration_template_success_html_content = (
  221. registration_template_success_html_template.render()
  222. )
  223. self.email_add_threepid_template_success_html_content = (
  224. add_threepid_template_success_html_template.render()
  225. )
  226. if self.email_enable_notifs:
  227. missing = []
  228. if not self.email_notif_from:
  229. missing.append("email.notif_from")
  230. if missing:
  231. raise ConfigError(
  232. "email.enable_notifs is True but required keys are missing: %s"
  233. % (", ".join(missing),)
  234. )
  235. notif_template_html = email_config.get(
  236. "notif_template_html", "notif_mail.html"
  237. )
  238. notif_template_text = email_config.get(
  239. "notif_template_text", "notif_mail.txt"
  240. )
  241. (
  242. self.email_notif_template_html,
  243. self.email_notif_template_text,
  244. ) = self.read_templates(
  245. [notif_template_html, notif_template_text],
  246. (
  247. td
  248. for td in (
  249. self.root.server.custom_template_directory,
  250. template_dir,
  251. )
  252. if td
  253. ), # Filter out template_dir if not provided
  254. )
  255. self.email_notif_for_new_users = email_config.get(
  256. "notif_for_new_users", True
  257. )
  258. self.email_riot_base_url = email_config.get(
  259. "client_base_url", email_config.get("riot_base_url", None)
  260. )
  261. # The amount of time we always wait before ever emailing about a notification
  262. # (to give the user a chance to respond to other push or notice the window)
  263. self.notif_delay_before_mail_ms = Config.parse_duration(
  264. email_config.get("notif_delay_before_mail", "10m")
  265. )
  266. if self.root.account_validity.account_validity_renew_by_email_enabled:
  267. expiry_template_html = email_config.get(
  268. "expiry_template_html", "notice_expiry.html"
  269. )
  270. expiry_template_text = email_config.get(
  271. "expiry_template_text", "notice_expiry.txt"
  272. )
  273. (
  274. self.account_validity_template_html,
  275. self.account_validity_template_text,
  276. ) = self.read_templates(
  277. [expiry_template_html, expiry_template_text],
  278. (
  279. td
  280. for td in (
  281. self.root.server.custom_template_directory,
  282. template_dir,
  283. )
  284. if td
  285. ), # Filter out template_dir if not provided
  286. )
  287. subjects_config = email_config.get("subjects", {})
  288. subjects = {}
  289. for key, default in DEFAULT_SUBJECTS.items():
  290. subjects[key] = subjects_config.get(key, default)
  291. self.email_subjects = EmailSubjectConfig(**subjects)
  292. # The invite client location should be a HTTP(S) URL or None.
  293. self.invite_client_location = email_config.get("invite_client_location") or None
  294. if self.invite_client_location:
  295. if not isinstance(self.invite_client_location, str):
  296. raise ConfigError(
  297. "Config option email.invite_client_location must be type str"
  298. )
  299. if not (
  300. self.invite_client_location.startswith("http://")
  301. or self.invite_client_location.startswith("https://")
  302. ):
  303. raise ConfigError(
  304. "Config option email.invite_client_location must be a http or https URL",
  305. path=("email", "invite_client_location"),
  306. )