emailconfig.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. import attr
  22. from ._base import Config, ConfigError
  23. logger = logging.getLogger(__name__)
  24. MISSING_PASSWORD_RESET_CONFIG_ERROR = """\
  25. Password reset emails are enabled on this homeserver due to a partial
  26. 'email' block. However, the following required keys are missing:
  27. %s
  28. """
  29. DEFAULT_SUBJECTS = {
  30. "message_from_person_in_room": "[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...",
  31. "message_from_person": "[%(app)s] You have a message on %(app)s from %(person)s...",
  32. "messages_from_person": "[%(app)s] You have messages on %(app)s from %(person)s...",
  33. "messages_in_room": "[%(app)s] You have messages on %(app)s in the %(room)s room...",
  34. "messages_in_room_and_others": "[%(app)s] You have messages on %(app)s in the %(room)s room and others...",
  35. "messages_from_person_and_others": "[%(app)s] You have messages on %(app)s from %(person)s and others...",
  36. "invite_from_person": "[%(app)s] %(person)s has invited you to chat on %(app)s...",
  37. "invite_from_person_to_room": "[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...",
  38. "invite_from_person_to_space": "[%(app)s] %(person)s has invited you to join the %(space)s space on %(app)s...",
  39. "password_reset": "[%(server_name)s] Password reset",
  40. "email_validation": "[%(server_name)s] Validate your email",
  41. }
  42. LEGACY_TEMPLATE_DIR_WARNING = """
  43. This server's configuration file is using the deprecated 'template_dir' setting in the
  44. 'email' section. Support for this setting has been deprecated and will be removed in a
  45. future version of Synapse. Server admins should instead use the new
  46. 'custom_templates_directory' setting documented here:
  47. https://matrix-org.github.io/synapse/latest/templates.html
  48. ---------------------------------------------------------------------------------------"""
  49. @attr.s(slots=True, frozen=True)
  50. class EmailSubjectConfig:
  51. message_from_person_in_room = attr.ib(type=str)
  52. message_from_person = attr.ib(type=str)
  53. messages_from_person = attr.ib(type=str)
  54. messages_in_room = attr.ib(type=str)
  55. messages_in_room_and_others = attr.ib(type=str)
  56. messages_from_person_and_others = attr.ib(type=str)
  57. invite_from_person = attr.ib(type=str)
  58. invite_from_person_to_room = attr.ib(type=str)
  59. invite_from_person_to_space = attr.ib(type=str)
  60. password_reset = attr.ib(type=str)
  61. email_validation = attr.ib(type=str)
  62. class EmailConfig(Config):
  63. section = "email"
  64. def read_config(self, config, **kwargs):
  65. # TODO: We should separate better the email configuration from the notification
  66. # and account validity config.
  67. self.email_enable_notifs = False
  68. email_config = config.get("email")
  69. if email_config is None:
  70. email_config = {}
  71. self.email_smtp_host = email_config.get("smtp_host", "localhost")
  72. self.email_smtp_port = email_config.get("smtp_port", 25)
  73. self.email_smtp_user = email_config.get("smtp_user", None)
  74. self.email_smtp_pass = email_config.get("smtp_pass", None)
  75. self.require_transport_security = email_config.get(
  76. "require_transport_security", False
  77. )
  78. self.enable_smtp_tls = email_config.get("enable_tls", True)
  79. if self.require_transport_security and not self.enable_smtp_tls:
  80. raise ConfigError(
  81. "email.require_transport_security requires email.enable_tls to be true"
  82. )
  83. if "app_name" in email_config:
  84. self.email_app_name = email_config["app_name"]
  85. else:
  86. self.email_app_name = "Matrix"
  87. # TODO: Rename notif_from to something more generic, or have a separate
  88. # from for password resets, message notifications, etc?
  89. # Currently the email section is a bit bogged down with settings for
  90. # multiple functions. Would be good to split it out into separate
  91. # sections and only put the common ones under email:
  92. self.email_notif_from = email_config.get("notif_from", None)
  93. if self.email_notif_from is not None:
  94. # make sure it's valid
  95. parsed = email.utils.parseaddr(self.email_notif_from)
  96. if parsed[1] == "":
  97. raise RuntimeError("Invalid notif_from address")
  98. # A user-configurable template directory
  99. template_dir = email_config.get("template_dir")
  100. if template_dir is not None:
  101. logger.warning(LEGACY_TEMPLATE_DIR_WARNING)
  102. if isinstance(template_dir, str):
  103. # We need an absolute path, because we change directory after starting (and
  104. # we don't yet know what auxiliary templates like mail.css we will need).
  105. template_dir = os.path.abspath(template_dir)
  106. elif template_dir is not None:
  107. # If template_dir is something other than a str or None, warn the user
  108. raise ConfigError("Config option email.template_dir must be type str")
  109. self.email_enable_notifs = email_config.get("enable_notifs", False)
  110. self.threepid_behaviour_email = (
  111. # Have Synapse handle the email sending if account_threepid_delegates.email
  112. # is not defined
  113. # msisdn is currently always remote while Synapse does not support any method of
  114. # sending SMS messages
  115. ThreepidBehaviour.REMOTE
  116. if self.root.registration.account_threepid_delegate_email
  117. else ThreepidBehaviour.LOCAL
  118. )
  119. if config.get("trust_identity_server_for_password_resets"):
  120. raise ConfigError(
  121. 'The config option "trust_identity_server_for_password_resets" '
  122. 'has been replaced by "account_threepid_delegate". '
  123. "Please consult the sample config at docs/sample_config.yaml for "
  124. "details and update your config file."
  125. )
  126. self.local_threepid_handling_disabled_due_to_email_config = False
  127. if (
  128. self.threepid_behaviour_email == ThreepidBehaviour.LOCAL
  129. and email_config == {}
  130. ):
  131. # We cannot warn the user this has happened here
  132. # Instead do so when a user attempts to reset their password
  133. self.local_threepid_handling_disabled_due_to_email_config = True
  134. self.threepid_behaviour_email = ThreepidBehaviour.OFF
  135. # Get lifetime of a validation token in milliseconds
  136. self.email_validation_token_lifetime = self.parse_duration(
  137. email_config.get("validation_token_lifetime", "1h")
  138. )
  139. if self.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  140. missing = []
  141. if not self.email_notif_from:
  142. missing.append("email.notif_from")
  143. if missing:
  144. raise ConfigError(
  145. MISSING_PASSWORD_RESET_CONFIG_ERROR % (", ".join(missing),)
  146. )
  147. # These email templates have placeholders in them, and thus must be
  148. # parsed using a templating engine during a request
  149. password_reset_template_html = email_config.get(
  150. "password_reset_template_html", "password_reset.html"
  151. )
  152. password_reset_template_text = email_config.get(
  153. "password_reset_template_text", "password_reset.txt"
  154. )
  155. registration_template_html = email_config.get(
  156. "registration_template_html", "registration.html"
  157. )
  158. registration_template_text = email_config.get(
  159. "registration_template_text", "registration.txt"
  160. )
  161. add_threepid_template_html = email_config.get(
  162. "add_threepid_template_html", "add_threepid.html"
  163. )
  164. add_threepid_template_text = email_config.get(
  165. "add_threepid_template_text", "add_threepid.txt"
  166. )
  167. password_reset_template_failure_html = email_config.get(
  168. "password_reset_template_failure_html", "password_reset_failure.html"
  169. )
  170. registration_template_failure_html = email_config.get(
  171. "registration_template_failure_html", "registration_failure.html"
  172. )
  173. add_threepid_template_failure_html = email_config.get(
  174. "add_threepid_template_failure_html", "add_threepid_failure.html"
  175. )
  176. # These templates do not support any placeholder variables, so we
  177. # will read them from disk once during setup
  178. password_reset_template_success_html = email_config.get(
  179. "password_reset_template_success_html", "password_reset_success.html"
  180. )
  181. registration_template_success_html = email_config.get(
  182. "registration_template_success_html", "registration_success.html"
  183. )
  184. add_threepid_template_success_html = email_config.get(
  185. "add_threepid_template_success_html", "add_threepid_success.html"
  186. )
  187. # Read all templates from disk
  188. (
  189. self.email_password_reset_template_html,
  190. self.email_password_reset_template_text,
  191. self.email_registration_template_html,
  192. self.email_registration_template_text,
  193. self.email_add_threepid_template_html,
  194. self.email_add_threepid_template_text,
  195. self.email_password_reset_template_confirmation_html,
  196. self.email_password_reset_template_failure_html,
  197. self.email_registration_template_failure_html,
  198. self.email_add_threepid_template_failure_html,
  199. password_reset_template_success_html_template,
  200. registration_template_success_html_template,
  201. add_threepid_template_success_html_template,
  202. ) = self.read_templates(
  203. [
  204. password_reset_template_html,
  205. password_reset_template_text,
  206. registration_template_html,
  207. registration_template_text,
  208. add_threepid_template_html,
  209. add_threepid_template_text,
  210. "password_reset_confirmation.html",
  211. password_reset_template_failure_html,
  212. registration_template_failure_html,
  213. add_threepid_template_failure_html,
  214. password_reset_template_success_html,
  215. registration_template_success_html,
  216. add_threepid_template_success_html,
  217. ],
  218. (
  219. td
  220. for td in (
  221. self.root.server.custom_template_directory,
  222. template_dir,
  223. )
  224. if td
  225. ), # Filter out template_dir if not provided
  226. )
  227. # Render templates that do not contain any placeholders
  228. self.email_password_reset_template_success_html_content = (
  229. password_reset_template_success_html_template.render()
  230. )
  231. self.email_registration_template_success_html_content = (
  232. registration_template_success_html_template.render()
  233. )
  234. self.email_add_threepid_template_success_html_content = (
  235. add_threepid_template_success_html_template.render()
  236. )
  237. if self.email_enable_notifs:
  238. missing = []
  239. if not self.email_notif_from:
  240. missing.append("email.notif_from")
  241. if missing:
  242. raise ConfigError(
  243. "email.enable_notifs is True but required keys are missing: %s"
  244. % (", ".join(missing),)
  245. )
  246. notif_template_html = email_config.get(
  247. "notif_template_html", "notif_mail.html"
  248. )
  249. notif_template_text = email_config.get(
  250. "notif_template_text", "notif_mail.txt"
  251. )
  252. (
  253. self.email_notif_template_html,
  254. self.email_notif_template_text,
  255. ) = self.read_templates(
  256. [notif_template_html, notif_template_text],
  257. (
  258. td
  259. for td in (
  260. self.root.server.custom_template_directory,
  261. template_dir,
  262. )
  263. if td
  264. ), # Filter out template_dir if not provided
  265. )
  266. self.email_notif_for_new_users = email_config.get(
  267. "notif_for_new_users", True
  268. )
  269. self.email_riot_base_url = email_config.get(
  270. "client_base_url", email_config.get("riot_base_url", None)
  271. )
  272. if self.root.account_validity.account_validity_renew_by_email_enabled:
  273. expiry_template_html = email_config.get(
  274. "expiry_template_html", "notice_expiry.html"
  275. )
  276. expiry_template_text = email_config.get(
  277. "expiry_template_text", "notice_expiry.txt"
  278. )
  279. (
  280. self.account_validity_template_html,
  281. self.account_validity_template_text,
  282. ) = self.read_templates(
  283. [expiry_template_html, expiry_template_text],
  284. (
  285. td
  286. for td in (
  287. self.root.server.custom_template_directory,
  288. template_dir,
  289. )
  290. if td
  291. ), # Filter out template_dir if not provided
  292. )
  293. subjects_config = email_config.get("subjects", {})
  294. subjects = {}
  295. for key, default in DEFAULT_SUBJECTS.items():
  296. subjects[key] = subjects_config.get(key, default)
  297. self.email_subjects = EmailSubjectConfig(**subjects)
  298. # The invite client location should be a HTTP(S) URL or None.
  299. self.invite_client_location = email_config.get("invite_client_location") or None
  300. if self.invite_client_location:
  301. if not isinstance(self.invite_client_location, str):
  302. raise ConfigError(
  303. "Config option email.invite_client_location must be type str"
  304. )
  305. if not (
  306. self.invite_client_location.startswith("http://")
  307. or self.invite_client_location.startswith("https://")
  308. ):
  309. raise ConfigError(
  310. "Config option email.invite_client_location must be a http or https URL",
  311. path=("email", "invite_client_location"),
  312. )
  313. def generate_config_section(self, config_dir_path, server_name, **kwargs):
  314. return (
  315. """\
  316. # Configuration for sending emails from Synapse.
  317. #
  318. # Server admins can configure custom templates for email content. See
  319. # https://matrix-org.github.io/synapse/latest/templates.html for more information.
  320. #
  321. email:
  322. # The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.
  323. #
  324. #smtp_host: mail.server
  325. # The port on the mail server for outgoing SMTP. Defaults to 25.
  326. #
  327. #smtp_port: 587
  328. # Username/password for authentication to the SMTP server. By default, no
  329. # authentication is attempted.
  330. #
  331. #smtp_user: "exampleusername"
  332. #smtp_pass: "examplepassword"
  333. # Uncomment the following to require TLS transport security for SMTP.
  334. # By default, Synapse will connect over plain text, and will then switch to
  335. # TLS via STARTTLS *if the SMTP server supports it*. If this option is set,
  336. # Synapse will refuse to connect unless the server supports STARTTLS.
  337. #
  338. #require_transport_security: true
  339. # Uncomment the following to disable TLS for SMTP.
  340. #
  341. # By default, if the server supports TLS, it will be used, and the server
  342. # must present a certificate that is valid for 'smtp_host'. If this option
  343. # is set to false, TLS will not be used.
  344. #
  345. #enable_tls: false
  346. # notif_from defines the "From" address to use when sending emails.
  347. # It must be set if email sending is enabled.
  348. #
  349. # The placeholder '%%(app)s' will be replaced by the application name,
  350. # which is normally 'app_name' (below), but may be overridden by the
  351. # Matrix client application.
  352. #
  353. # Note that the placeholder must be written '%%(app)s', including the
  354. # trailing 's'.
  355. #
  356. #notif_from: "Your Friendly %%(app)s homeserver <noreply@example.com>"
  357. # app_name defines the default value for '%%(app)s' in notif_from and email
  358. # subjects. It defaults to 'Matrix'.
  359. #
  360. #app_name: my_branded_matrix_server
  361. # Uncomment the following to enable sending emails for messages that the user
  362. # has missed. Disabled by default.
  363. #
  364. #enable_notifs: true
  365. # Uncomment the following to disable automatic subscription to email
  366. # notifications for new users. Enabled by default.
  367. #
  368. #notif_for_new_users: false
  369. # Custom URL for client links within the email notifications. By default
  370. # links will be based on "https://matrix.to".
  371. #
  372. # (This setting used to be called riot_base_url; the old name is still
  373. # supported for backwards-compatibility but is now deprecated.)
  374. #
  375. #client_base_url: "http://localhost/riot"
  376. # Configure the time that a validation email will expire after sending.
  377. # Defaults to 1h.
  378. #
  379. #validation_token_lifetime: 15m
  380. # The web client location to direct users to during an invite. This is passed
  381. # to the identity server as the org.matrix.web_client_location key. Defaults
  382. # to unset, giving no guidance to the identity server.
  383. #
  384. #invite_client_location: https://app.element.io
  385. # Subjects to use when sending emails from Synapse.
  386. #
  387. # The placeholder '%%(app)s' will be replaced with the value of the 'app_name'
  388. # setting above, or by a value dictated by the Matrix client application.
  389. #
  390. # If a subject isn't overridden in this configuration file, the value used as
  391. # its example will be used.
  392. #
  393. #subjects:
  394. # Subjects for notification emails.
  395. #
  396. # On top of the '%%(app)s' placeholder, these can use the following
  397. # placeholders:
  398. #
  399. # * '%%(person)s', which will be replaced by the display name of the user(s)
  400. # that sent the message(s), e.g. "Alice and Bob".
  401. # * '%%(room)s', which will be replaced by the name of the room the
  402. # message(s) have been sent to, e.g. "My super room".
  403. #
  404. # See the example provided for each setting to see which placeholder can be
  405. # used and how to use them.
  406. #
  407. # Subject to use to notify about one message from one or more user(s) in a
  408. # room which has a name.
  409. #message_from_person_in_room: "%(message_from_person_in_room)s"
  410. #
  411. # Subject to use to notify about one message from one or more user(s) in a
  412. # room which doesn't have a name.
  413. #message_from_person: "%(message_from_person)s"
  414. #
  415. # Subject to use to notify about multiple messages from one or more users in
  416. # a room which doesn't have a name.
  417. #messages_from_person: "%(messages_from_person)s"
  418. #
  419. # Subject to use to notify about multiple messages in a room which has a
  420. # name.
  421. #messages_in_room: "%(messages_in_room)s"
  422. #
  423. # Subject to use to notify about multiple messages in multiple rooms.
  424. #messages_in_room_and_others: "%(messages_in_room_and_others)s"
  425. #
  426. # Subject to use to notify about multiple messages from multiple persons in
  427. # multiple rooms. This is similar to the setting above except it's used when
  428. # the room in which the notification was triggered has no name.
  429. #messages_from_person_and_others: "%(messages_from_person_and_others)s"
  430. #
  431. # Subject to use to notify about an invite to a room which has a name.
  432. #invite_from_person_to_room: "%(invite_from_person_to_room)s"
  433. #
  434. # Subject to use to notify about an invite to a room which doesn't have a
  435. # name.
  436. #invite_from_person: "%(invite_from_person)s"
  437. # Subject for emails related to account administration.
  438. #
  439. # On top of the '%%(app)s' placeholder, these one can use the
  440. # '%%(server_name)s' placeholder, which will be replaced by the value of the
  441. # 'server_name' setting in your Synapse configuration.
  442. #
  443. # Subject to use when sending a password reset email.
  444. #password_reset: "%(password_reset)s"
  445. #
  446. # Subject to use when sending a verification email to assert an address's
  447. # ownership.
  448. #email_validation: "%(email_validation)s"
  449. """
  450. % DEFAULT_SUBJECTS
  451. )
  452. class ThreepidBehaviour(Enum):
  453. """
  454. Enum to define the behaviour of Synapse with regards to when it contacts an identity
  455. server for 3pid registration and password resets
  456. REMOTE = use an external server to send tokens
  457. LOCAL = send tokens ourselves
  458. OFF = disable registration via 3pid and password resets
  459. """
  460. REMOTE = "remote"
  461. LOCAL = "local"
  462. OFF = "off"