emailconfig.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015-2016 OpenMarket Ltd
  3. # Copyright 2017-2018 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. from __future__ import print_function
  18. # This file can't be called email.py because if it is, we cannot:
  19. import email.utils
  20. import os
  21. from enum import Enum
  22. from typing import Optional
  23. import pkg_resources
  24. from ._base import Config, ConfigError
  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. class EmailConfig(Config):
  31. section = "email"
  32. def read_config(self, config, **kwargs):
  33. # TODO: We should separate better the email configuration from the notification
  34. # and account validity config.
  35. self.email_enable_notifs = False
  36. email_config = config.get("email")
  37. if email_config is None:
  38. email_config = {}
  39. self.email_smtp_host = email_config.get("smtp_host", "localhost")
  40. self.email_smtp_port = email_config.get("smtp_port", 25)
  41. self.email_smtp_user = email_config.get("smtp_user", None)
  42. self.email_smtp_pass = email_config.get("smtp_pass", None)
  43. self.require_transport_security = email_config.get(
  44. "require_transport_security", False
  45. )
  46. if "app_name" in email_config:
  47. self.email_app_name = email_config["app_name"]
  48. else:
  49. self.email_app_name = "Matrix"
  50. # TODO: Rename notif_from to something more generic, or have a separate
  51. # from for password resets, message notifications, etc?
  52. # Currently the email section is a bit bogged down with settings for
  53. # multiple functions. Would be good to split it out into separate
  54. # sections and only put the common ones under email:
  55. self.email_notif_from = email_config.get("notif_from", None)
  56. if self.email_notif_from is not None:
  57. # make sure it's valid
  58. parsed = email.utils.parseaddr(self.email_notif_from)
  59. if parsed[1] == "":
  60. raise RuntimeError("Invalid notif_from address")
  61. template_dir = email_config.get("template_dir")
  62. # we need an absolute path, because we change directory after starting (and
  63. # we don't yet know what auxilliary templates like mail.css we will need).
  64. # (Note that loading as package_resources with jinja.PackageLoader doesn't
  65. # work for the same reason.)
  66. if not template_dir:
  67. template_dir = pkg_resources.resource_filename("synapse", "res/templates")
  68. self.email_template_dir = os.path.abspath(template_dir)
  69. self.email_enable_notifs = email_config.get("enable_notifs", False)
  70. account_validity_config = config.get("account_validity") or {}
  71. account_validity_renewal_enabled = account_validity_config.get("renew_at")
  72. self.threepid_behaviour_email = (
  73. # Have Synapse handle the email sending if account_threepid_delegates.email
  74. # is not defined
  75. # msisdn is currently always remote while Synapse does not support any method of
  76. # sending SMS messages
  77. ThreepidBehaviour.REMOTE
  78. if self.account_threepid_delegate_email
  79. else ThreepidBehaviour.LOCAL
  80. )
  81. # Prior to Synapse v1.4.0, there was another option that defined whether Synapse would
  82. # use an identity server to password reset tokens on its behalf. We now warn the user
  83. # if they have this set and tell them to use the updated option, while using a default
  84. # identity server in the process.
  85. self.using_identity_server_from_trusted_list = False
  86. if (
  87. not self.account_threepid_delegate_email
  88. and config.get("trust_identity_server_for_password_resets", False) is True
  89. ):
  90. # Use the first entry in self.trusted_third_party_id_servers instead
  91. if self.trusted_third_party_id_servers:
  92. # XXX: It's a little confusing that account_threepid_delegate_email is modified
  93. # both in RegistrationConfig and here. We should factor this bit out
  94. first_trusted_identity_server = self.trusted_third_party_id_servers[0]
  95. # trusted_third_party_id_servers does not contain a scheme whereas
  96. # account_threepid_delegate_email is expected to. Presume https
  97. self.account_threepid_delegate_email = (
  98. "https://" + first_trusted_identity_server
  99. ) # type: Optional[str]
  100. self.using_identity_server_from_trusted_list = True
  101. else:
  102. raise ConfigError(
  103. "Attempted to use an identity server from"
  104. '"trusted_third_party_id_servers" but it is empty.'
  105. )
  106. self.local_threepid_handling_disabled_due_to_email_config = False
  107. if (
  108. self.threepid_behaviour_email == ThreepidBehaviour.LOCAL
  109. and email_config == {}
  110. ):
  111. # We cannot warn the user this has happened here
  112. # Instead do so when a user attempts to reset their password
  113. self.local_threepid_handling_disabled_due_to_email_config = True
  114. self.threepid_behaviour_email = ThreepidBehaviour.OFF
  115. # Get lifetime of a validation token in milliseconds
  116. self.email_validation_token_lifetime = self.parse_duration(
  117. email_config.get("validation_token_lifetime", "1h")
  118. )
  119. if (
  120. self.email_enable_notifs
  121. or account_validity_renewal_enabled
  122. or self.threepid_behaviour_email == ThreepidBehaviour.LOCAL
  123. ):
  124. # make sure we can import the required deps
  125. import jinja2
  126. import bleach
  127. # prevent unused warnings
  128. jinja2
  129. bleach
  130. if self.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  131. missing = []
  132. if not self.email_notif_from:
  133. missing.append("email.notif_from")
  134. # public_baseurl is required to build password reset and validation links that
  135. # will be emailed to users
  136. if config.get("public_baseurl") is None:
  137. missing.append("public_baseurl")
  138. if missing:
  139. raise ConfigError(
  140. MISSING_PASSWORD_RESET_CONFIG_ERROR % (", ".join(missing),)
  141. )
  142. # These email templates have placeholders in them, and thus must be
  143. # parsed using a templating engine during a request
  144. self.email_password_reset_template_html = email_config.get(
  145. "password_reset_template_html", "password_reset.html"
  146. )
  147. self.email_password_reset_template_text = email_config.get(
  148. "password_reset_template_text", "password_reset.txt"
  149. )
  150. self.email_registration_template_html = email_config.get(
  151. "registration_template_html", "registration.html"
  152. )
  153. self.email_registration_template_text = email_config.get(
  154. "registration_template_text", "registration.txt"
  155. )
  156. self.email_add_threepid_template_html = email_config.get(
  157. "add_threepid_template_html", "add_threepid.html"
  158. )
  159. self.email_add_threepid_template_text = email_config.get(
  160. "add_threepid_template_text", "add_threepid.txt"
  161. )
  162. self.email_password_reset_template_failure_html = email_config.get(
  163. "password_reset_template_failure_html", "password_reset_failure.html"
  164. )
  165. self.email_registration_template_failure_html = email_config.get(
  166. "registration_template_failure_html", "registration_failure.html"
  167. )
  168. self.email_add_threepid_template_failure_html = email_config.get(
  169. "add_threepid_template_failure_html", "add_threepid_failure.html"
  170. )
  171. # These templates do not support any placeholder variables, so we
  172. # will read them from disk once during setup
  173. email_password_reset_template_success_html = email_config.get(
  174. "password_reset_template_success_html", "password_reset_success.html"
  175. )
  176. email_registration_template_success_html = email_config.get(
  177. "registration_template_success_html", "registration_success.html"
  178. )
  179. email_add_threepid_template_success_html = email_config.get(
  180. "add_threepid_template_success_html", "add_threepid_success.html"
  181. )
  182. # Check templates exist
  183. for f in [
  184. self.email_password_reset_template_html,
  185. self.email_password_reset_template_text,
  186. self.email_registration_template_html,
  187. self.email_registration_template_text,
  188. self.email_add_threepid_template_html,
  189. self.email_add_threepid_template_text,
  190. self.email_password_reset_template_failure_html,
  191. self.email_registration_template_failure_html,
  192. self.email_add_threepid_template_failure_html,
  193. email_password_reset_template_success_html,
  194. email_registration_template_success_html,
  195. email_add_threepid_template_success_html,
  196. ]:
  197. p = os.path.join(self.email_template_dir, f)
  198. if not os.path.isfile(p):
  199. raise ConfigError("Unable to find template file %s" % (p,))
  200. # Retrieve content of web templates
  201. filepath = os.path.join(
  202. self.email_template_dir, email_password_reset_template_success_html
  203. )
  204. self.email_password_reset_template_success_html = self.read_file(
  205. filepath, "email.password_reset_template_success_html"
  206. )
  207. filepath = os.path.join(
  208. self.email_template_dir, email_registration_template_success_html
  209. )
  210. self.email_registration_template_success_html_content = self.read_file(
  211. filepath, "email.registration_template_success_html"
  212. )
  213. filepath = os.path.join(
  214. self.email_template_dir, email_add_threepid_template_success_html
  215. )
  216. self.email_add_threepid_template_success_html_content = self.read_file(
  217. filepath, "email.add_threepid_template_success_html"
  218. )
  219. if self.email_enable_notifs:
  220. missing = []
  221. if not self.email_notif_from:
  222. missing.append("email.notif_from")
  223. if config.get("public_baseurl") is None:
  224. missing.append("public_baseurl")
  225. if missing:
  226. raise ConfigError(
  227. "email.enable_notifs is True but required keys are missing: %s"
  228. % (", ".join(missing),)
  229. )
  230. self.email_notif_template_html = email_config.get(
  231. "notif_template_html", "notif_mail.html"
  232. )
  233. self.email_notif_template_text = email_config.get(
  234. "notif_template_text", "notif_mail.txt"
  235. )
  236. for f in self.email_notif_template_text, self.email_notif_template_html:
  237. p = os.path.join(self.email_template_dir, f)
  238. if not os.path.isfile(p):
  239. raise ConfigError("Unable to find email template file %s" % (p,))
  240. self.email_notif_for_new_users = email_config.get(
  241. "notif_for_new_users", True
  242. )
  243. self.email_riot_base_url = email_config.get(
  244. "client_base_url", email_config.get("riot_base_url", None)
  245. )
  246. if account_validity_renewal_enabled:
  247. self.email_expiry_template_html = email_config.get(
  248. "expiry_template_html", "notice_expiry.html"
  249. )
  250. self.email_expiry_template_text = email_config.get(
  251. "expiry_template_text", "notice_expiry.txt"
  252. )
  253. for f in self.email_expiry_template_text, self.email_expiry_template_html:
  254. p = os.path.join(self.email_template_dir, f)
  255. if not os.path.isfile(p):
  256. raise ConfigError("Unable to find email template file %s" % (p,))
  257. def generate_config_section(self, config_dir_path, server_name, **kwargs):
  258. return """\
  259. # Configuration for sending emails from Synapse.
  260. #
  261. email:
  262. # The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.
  263. #
  264. #smtp_host: mail.server
  265. # The port on the mail server for outgoing SMTP. Defaults to 25.
  266. #
  267. #smtp_port: 587
  268. # Username/password for authentication to the SMTP server. By default, no
  269. # authentication is attempted.
  270. #
  271. #smtp_user: "exampleusername"
  272. #smtp_pass: "examplepassword"
  273. # Uncomment the following to require TLS transport security for SMTP.
  274. # By default, Synapse will connect over plain text, and will then switch to
  275. # TLS via STARTTLS *if the SMTP server supports it*. If this option is set,
  276. # Synapse will refuse to connect unless the server supports STARTTLS.
  277. #
  278. #require_transport_security: true
  279. # notif_from defines the "From" address to use when sending emails.
  280. # It must be set if email sending is enabled.
  281. #
  282. # The placeholder '%(app)s' will be replaced by the application name,
  283. # which is normally 'app_name' (below), but may be overridden by the
  284. # Matrix client application.
  285. #
  286. # Note that the placeholder must be written '%(app)s', including the
  287. # trailing 's'.
  288. #
  289. #notif_from: "Your Friendly %(app)s homeserver <noreply@example.com>"
  290. # app_name defines the default value for '%(app)s' in notif_from. It
  291. # defaults to 'Matrix'.
  292. #
  293. #app_name: my_branded_matrix_server
  294. # Uncomment the following to enable sending emails for messages that the user
  295. # has missed. Disabled by default.
  296. #
  297. #enable_notifs: true
  298. # Uncomment the following to disable automatic subscription to email
  299. # notifications for new users. Enabled by default.
  300. #
  301. #notif_for_new_users: false
  302. # Custom URL for client links within the email notifications. By default
  303. # links will be based on "https://matrix.to".
  304. #
  305. # (This setting used to be called riot_base_url; the old name is still
  306. # supported for backwards-compatibility but is now deprecated.)
  307. #
  308. #client_base_url: "http://localhost/riot"
  309. # Configure the time that a validation email will expire after sending.
  310. # Defaults to 1h.
  311. #
  312. #validation_token_lifetime: 15m
  313. # Directory in which Synapse will try to find the template files below.
  314. # If not set, default templates from within the Synapse package will be used.
  315. #
  316. # DO NOT UNCOMMENT THIS SETTING unless you want to customise the templates.
  317. # If you *do* uncomment it, you will need to make sure that all the templates
  318. # below are in the directory.
  319. #
  320. # Synapse will look for the following templates in this directory:
  321. #
  322. # * The contents of email notifications of missed events: 'notif_mail.html' and
  323. # 'notif_mail.txt'.
  324. #
  325. # * The contents of account expiry notice emails: 'notice_expiry.html' and
  326. # 'notice_expiry.txt'.
  327. #
  328. # * The contents of password reset emails sent by the homeserver:
  329. # 'password_reset.html' and 'password_reset.txt'
  330. #
  331. # * HTML pages for success and failure that a user will see when they follow
  332. # the link in the password reset email: 'password_reset_success.html' and
  333. # 'password_reset_failure.html'
  334. #
  335. # * The contents of address verification emails sent during registration:
  336. # 'registration.html' and 'registration.txt'
  337. #
  338. # * HTML pages for success and failure that a user will see when they follow
  339. # the link in an address verification email sent during registration:
  340. # 'registration_success.html' and 'registration_failure.html'
  341. #
  342. # * The contents of address verification emails sent when an address is added
  343. # to a Matrix account: 'add_threepid.html' and 'add_threepid.txt'
  344. #
  345. # * HTML pages for success and failure that a user will see when they follow
  346. # the link in an address verification email sent when an address is added
  347. # to a Matrix account: 'add_threepid_success.html' and
  348. # 'add_threepid_failure.html'
  349. #
  350. # You can see the default templates at:
  351. # https://github.com/matrix-org/synapse/tree/master/synapse/res/templates
  352. #
  353. #template_dir: "res/templates"
  354. """
  355. class ThreepidBehaviour(Enum):
  356. """
  357. Enum to define the behaviour of Synapse with regards to when it contacts an identity
  358. server for 3pid registration and password resets
  359. REMOTE = use an external server to send tokens
  360. LOCAL = send tokens ourselves
  361. OFF = disable registration via 3pid and password resets
  362. """
  363. REMOTE = "remote"
  364. LOCAL = "local"
  365. OFF = "off"