25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

378 lines
16 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 enum import Enum
  21. from typing import Any
  22. import attr
  23. from synapse.types import JsonDict
  24. from ._base import Config, ConfigError
  25. logger = logging.getLogger(__name__)
  26. MISSING_PASSWORD_RESET_CONFIG_ERROR = """\
  27. Password reset emails are enabled on this homeserver due to a partial
  28. 'email' block. However, the following required keys are missing:
  29. %s
  30. """
  31. DEFAULT_SUBJECTS = {
  32. "message_from_person_in_room": "[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...",
  33. "message_from_person": "[%(app)s] You have a message on %(app)s from %(person)s...",
  34. "messages_from_person": "[%(app)s] You have messages on %(app)s from %(person)s...",
  35. "messages_in_room": "[%(app)s] You have messages on %(app)s in the %(room)s room...",
  36. "messages_in_room_and_others": "[%(app)s] You have messages on %(app)s in the %(room)s room and others...",
  37. "messages_from_person_and_others": "[%(app)s] You have messages on %(app)s from %(person)s and others...",
  38. "invite_from_person": "[%(app)s] %(person)s has invited you to chat on %(app)s...",
  39. "invite_from_person_to_room": "[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...",
  40. "invite_from_person_to_space": "[%(app)s] %(person)s has invited you to join the %(space)s space on %(app)s...",
  41. "password_reset": "[%(server_name)s] Password reset",
  42. "email_validation": "[%(server_name)s] Validate your email",
  43. }
  44. LEGACY_TEMPLATE_DIR_WARNING = """
  45. This server's configuration file is using the deprecated 'template_dir' setting in the
  46. 'email' section. Support for this setting has been deprecated and will be removed in a
  47. future version of Synapse. Server admins should instead use the new
  48. 'custom_template_directory' setting documented here:
  49. https://matrix-org.github.io/synapse/latest/templates.html
  50. ---------------------------------------------------------------------------------------"""
  51. @attr.s(slots=True, frozen=True, auto_attribs=True)
  52. class EmailSubjectConfig:
  53. message_from_person_in_room: str
  54. message_from_person: str
  55. messages_from_person: str
  56. messages_in_room: str
  57. messages_in_room_and_others: str
  58. messages_from_person_and_others: str
  59. invite_from_person: str
  60. invite_from_person_to_room: str
  61. invite_from_person_to_space: str
  62. password_reset: str
  63. email_validation: str
  64. class EmailConfig(Config):
  65. section = "email"
  66. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  67. # TODO: We should separate better the email configuration from the notification
  68. # and account validity config.
  69. self.email_enable_notifs = False
  70. email_config = config.get("email")
  71. if email_config is None:
  72. email_config = {}
  73. self.force_tls = email_config.get("force_tls", False)
  74. self.email_smtp_host = email_config.get("smtp_host", "localhost")
  75. self.email_smtp_port = email_config.get(
  76. "smtp_port", 465 if self.force_tls else 25
  77. )
  78. self.email_smtp_user = email_config.get("smtp_user", None)
  79. self.email_smtp_pass = email_config.get("smtp_pass", None)
  80. self.require_transport_security = email_config.get(
  81. "require_transport_security", False
  82. )
  83. self.enable_smtp_tls = email_config.get("enable_tls", True)
  84. if self.force_tls and not self.enable_smtp_tls:
  85. raise ConfigError("email.force_tls requires email.enable_tls to be true")
  86. if self.require_transport_security and not self.enable_smtp_tls:
  87. raise ConfigError(
  88. "email.require_transport_security requires email.enable_tls to be true"
  89. )
  90. if "app_name" in email_config:
  91. self.email_app_name = email_config["app_name"]
  92. else:
  93. self.email_app_name = "Matrix"
  94. # TODO: Rename notif_from to something more generic, or have a separate
  95. # from for password resets, message notifications, etc?
  96. # Currently the email section is a bit bogged down with settings for
  97. # multiple functions. Would be good to split it out into separate
  98. # sections and only put the common ones under email:
  99. self.email_notif_from = email_config.get("notif_from", None)
  100. if self.email_notif_from is not None:
  101. # make sure it's valid
  102. parsed = email.utils.parseaddr(self.email_notif_from)
  103. if parsed[1] == "":
  104. raise RuntimeError("Invalid notif_from address")
  105. # A user-configurable template directory
  106. template_dir = email_config.get("template_dir")
  107. if template_dir is not None:
  108. logger.warning(LEGACY_TEMPLATE_DIR_WARNING)
  109. if isinstance(template_dir, str):
  110. # We need an absolute path, because we change directory after starting (and
  111. # we don't yet know what auxiliary templates like mail.css we will need).
  112. template_dir = os.path.abspath(template_dir)
  113. elif template_dir is not None:
  114. # If template_dir is something other than a str or None, warn the user
  115. raise ConfigError("Config option email.template_dir must be type str")
  116. self.email_enable_notifs = email_config.get("enable_notifs", False)
  117. self.threepid_behaviour_email = (
  118. # Have Synapse handle the email sending if account_threepid_delegates.email
  119. # is not defined
  120. # msisdn is currently always remote while Synapse does not support any method of
  121. # sending SMS messages
  122. ThreepidBehaviour.REMOTE
  123. if self.root.registration.account_threepid_delegate_email
  124. else ThreepidBehaviour.LOCAL
  125. )
  126. if config.get("trust_identity_server_for_password_resets"):
  127. raise ConfigError(
  128. 'The config option "trust_identity_server_for_password_resets" has been removed.'
  129. "Please consult the configuration manual at docs/usage/configuration/config_documentation.md for "
  130. "details and update your config file."
  131. )
  132. self.local_threepid_handling_disabled_due_to_email_config = False
  133. if (
  134. self.threepid_behaviour_email == ThreepidBehaviour.LOCAL
  135. and email_config == {}
  136. ):
  137. # We cannot warn the user this has happened here
  138. # Instead do so when a user attempts to reset their password
  139. self.local_threepid_handling_disabled_due_to_email_config = True
  140. self.threepid_behaviour_email = ThreepidBehaviour.OFF
  141. # Get lifetime of a validation token in milliseconds
  142. self.email_validation_token_lifetime = self.parse_duration(
  143. email_config.get("validation_token_lifetime", "1h")
  144. )
  145. if self.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  146. missing = []
  147. if not self.email_notif_from:
  148. missing.append("email.notif_from")
  149. if missing:
  150. raise ConfigError(
  151. MISSING_PASSWORD_RESET_CONFIG_ERROR % (", ".join(missing),)
  152. )
  153. # These email templates have placeholders in them, and thus must be
  154. # parsed using a templating engine during a request
  155. password_reset_template_html = email_config.get(
  156. "password_reset_template_html", "password_reset.html"
  157. )
  158. password_reset_template_text = email_config.get(
  159. "password_reset_template_text", "password_reset.txt"
  160. )
  161. registration_template_html = email_config.get(
  162. "registration_template_html", "registration.html"
  163. )
  164. registration_template_text = email_config.get(
  165. "registration_template_text", "registration.txt"
  166. )
  167. add_threepid_template_html = email_config.get(
  168. "add_threepid_template_html", "add_threepid.html"
  169. )
  170. add_threepid_template_text = email_config.get(
  171. "add_threepid_template_text", "add_threepid.txt"
  172. )
  173. password_reset_template_failure_html = email_config.get(
  174. "password_reset_template_failure_html", "password_reset_failure.html"
  175. )
  176. registration_template_failure_html = email_config.get(
  177. "registration_template_failure_html", "registration_failure.html"
  178. )
  179. add_threepid_template_failure_html = email_config.get(
  180. "add_threepid_template_failure_html", "add_threepid_failure.html"
  181. )
  182. # These templates do not support any placeholder variables, so we
  183. # will read them from disk once during setup
  184. password_reset_template_success_html = email_config.get(
  185. "password_reset_template_success_html", "password_reset_success.html"
  186. )
  187. registration_template_success_html = email_config.get(
  188. "registration_template_success_html", "registration_success.html"
  189. )
  190. add_threepid_template_success_html = email_config.get(
  191. "add_threepid_template_success_html", "add_threepid_success.html"
  192. )
  193. # Read all templates from disk
  194. (
  195. self.email_password_reset_template_html,
  196. self.email_password_reset_template_text,
  197. self.email_registration_template_html,
  198. self.email_registration_template_text,
  199. self.email_add_threepid_template_html,
  200. self.email_add_threepid_template_text,
  201. self.email_password_reset_template_confirmation_html,
  202. self.email_password_reset_template_failure_html,
  203. self.email_registration_template_failure_html,
  204. self.email_add_threepid_template_failure_html,
  205. password_reset_template_success_html_template,
  206. registration_template_success_html_template,
  207. add_threepid_template_success_html_template,
  208. ) = self.read_templates(
  209. [
  210. password_reset_template_html,
  211. password_reset_template_text,
  212. registration_template_html,
  213. registration_template_text,
  214. add_threepid_template_html,
  215. add_threepid_template_text,
  216. "password_reset_confirmation.html",
  217. password_reset_template_failure_html,
  218. registration_template_failure_html,
  219. add_threepid_template_failure_html,
  220. password_reset_template_success_html,
  221. registration_template_success_html,
  222. add_threepid_template_success_html,
  223. ],
  224. (
  225. td
  226. for td in (
  227. self.root.server.custom_template_directory,
  228. template_dir,
  229. )
  230. if td
  231. ), # Filter out template_dir if not provided
  232. )
  233. # Render templates that do not contain any placeholders
  234. self.email_password_reset_template_success_html_content = (
  235. password_reset_template_success_html_template.render()
  236. )
  237. self.email_registration_template_success_html_content = (
  238. registration_template_success_html_template.render()
  239. )
  240. self.email_add_threepid_template_success_html_content = (
  241. add_threepid_template_success_html_template.render()
  242. )
  243. if self.email_enable_notifs:
  244. missing = []
  245. if not self.email_notif_from:
  246. missing.append("email.notif_from")
  247. if missing:
  248. raise ConfigError(
  249. "email.enable_notifs is True but required keys are missing: %s"
  250. % (", ".join(missing),)
  251. )
  252. notif_template_html = email_config.get(
  253. "notif_template_html", "notif_mail.html"
  254. )
  255. notif_template_text = email_config.get(
  256. "notif_template_text", "notif_mail.txt"
  257. )
  258. (
  259. self.email_notif_template_html,
  260. self.email_notif_template_text,
  261. ) = self.read_templates(
  262. [notif_template_html, notif_template_text],
  263. (
  264. td
  265. for td in (
  266. self.root.server.custom_template_directory,
  267. template_dir,
  268. )
  269. if td
  270. ), # Filter out template_dir if not provided
  271. )
  272. self.email_notif_for_new_users = email_config.get(
  273. "notif_for_new_users", True
  274. )
  275. self.email_riot_base_url = email_config.get(
  276. "client_base_url", email_config.get("riot_base_url", None)
  277. )
  278. if self.root.account_validity.account_validity_renew_by_email_enabled:
  279. expiry_template_html = email_config.get(
  280. "expiry_template_html", "notice_expiry.html"
  281. )
  282. expiry_template_text = email_config.get(
  283. "expiry_template_text", "notice_expiry.txt"
  284. )
  285. (
  286. self.account_validity_template_html,
  287. self.account_validity_template_text,
  288. ) = self.read_templates(
  289. [expiry_template_html, expiry_template_text],
  290. (
  291. td
  292. for td in (
  293. self.root.server.custom_template_directory,
  294. template_dir,
  295. )
  296. if td
  297. ), # Filter out template_dir if not provided
  298. )
  299. subjects_config = email_config.get("subjects", {})
  300. subjects = {}
  301. for key, default in DEFAULT_SUBJECTS.items():
  302. subjects[key] = subjects_config.get(key, default)
  303. self.email_subjects = EmailSubjectConfig(**subjects)
  304. # The invite client location should be a HTTP(S) URL or None.
  305. self.invite_client_location = email_config.get("invite_client_location") or None
  306. if self.invite_client_location:
  307. if not isinstance(self.invite_client_location, str):
  308. raise ConfigError(
  309. "Config option email.invite_client_location must be type str"
  310. )
  311. if not (
  312. self.invite_client_location.startswith("http://")
  313. or self.invite_client_location.startswith("https://")
  314. ):
  315. raise ConfigError(
  316. "Config option email.invite_client_location must be a http or https URL",
  317. path=("email", "invite_client_location"),
  318. )
  319. class ThreepidBehaviour(Enum):
  320. """
  321. Enum to define the behaviour of Synapse with regards to when it contacts an identity
  322. server for 3pid registration and password resets
  323. REMOTE = use an external server to send tokens
  324. LOCAL = send tokens ourselves
  325. OFF = disable registration via 3pid and password resets
  326. """
  327. REMOTE = "remote"
  328. LOCAL = "local"
  329. OFF = "off"