Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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