emailconfig.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. # Prior to Synapse v1.4.0, there was another option that defined whether Synapse would
  120. # use an identity server to password reset tokens on its behalf. We now warn the user
  121. # if they have this set and tell them to use the updated option, while using a default
  122. # identity server in the process.
  123. self.using_identity_server_from_trusted_list = False
  124. if (
  125. not self.root.registration.account_threepid_delegate_email
  126. and config.get("trust_identity_server_for_password_resets", False) is True
  127. ):
  128. # Use the first entry in self.trusted_third_party_id_servers instead
  129. if self.trusted_third_party_id_servers:
  130. # XXX: It's a little confusing that account_threepid_delegate_email is modified
  131. # both in RegistrationConfig and here. We should factor this bit out
  132. first_trusted_identity_server = self.trusted_third_party_id_servers[0]
  133. # trusted_third_party_id_servers does not contain a scheme whereas
  134. # account_threepid_delegate_email is expected to. Presume https
  135. self.root.registration.account_threepid_delegate_email = (
  136. "https://" + first_trusted_identity_server
  137. )
  138. self.using_identity_server_from_trusted_list = True
  139. else:
  140. raise ConfigError(
  141. "Attempted to use an identity server from"
  142. '"trusted_third_party_id_servers" but it is empty.'
  143. )
  144. self.local_threepid_handling_disabled_due_to_email_config = False
  145. if (
  146. self.threepid_behaviour_email == ThreepidBehaviour.LOCAL
  147. and email_config == {}
  148. ):
  149. # We cannot warn the user this has happened here
  150. # Instead do so when a user attempts to reset their password
  151. self.local_threepid_handling_disabled_due_to_email_config = True
  152. self.threepid_behaviour_email = ThreepidBehaviour.OFF
  153. # Get lifetime of a validation token in milliseconds
  154. self.email_validation_token_lifetime = self.parse_duration(
  155. email_config.get("validation_token_lifetime", "1h")
  156. )
  157. if self.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  158. missing = []
  159. if not self.email_notif_from:
  160. missing.append("email.notif_from")
  161. # public_baseurl is required to build password reset and validation links that
  162. # will be emailed to users
  163. if config.get("public_baseurl") is None:
  164. missing.append("public_baseurl")
  165. if missing:
  166. raise ConfigError(
  167. MISSING_PASSWORD_RESET_CONFIG_ERROR % (", ".join(missing),)
  168. )
  169. # These email templates have placeholders in them, and thus must be
  170. # parsed using a templating engine during a request
  171. password_reset_template_html = email_config.get(
  172. "password_reset_template_html", "password_reset.html"
  173. )
  174. password_reset_template_text = email_config.get(
  175. "password_reset_template_text", "password_reset.txt"
  176. )
  177. registration_template_html = email_config.get(
  178. "registration_template_html", "registration.html"
  179. )
  180. registration_template_text = email_config.get(
  181. "registration_template_text", "registration.txt"
  182. )
  183. add_threepid_template_html = email_config.get(
  184. "add_threepid_template_html", "add_threepid.html"
  185. )
  186. add_threepid_template_text = email_config.get(
  187. "add_threepid_template_text", "add_threepid.txt"
  188. )
  189. password_reset_template_failure_html = email_config.get(
  190. "password_reset_template_failure_html", "password_reset_failure.html"
  191. )
  192. registration_template_failure_html = email_config.get(
  193. "registration_template_failure_html", "registration_failure.html"
  194. )
  195. add_threepid_template_failure_html = email_config.get(
  196. "add_threepid_template_failure_html", "add_threepid_failure.html"
  197. )
  198. # These templates do not support any placeholder variables, so we
  199. # will read them from disk once during setup
  200. password_reset_template_success_html = email_config.get(
  201. "password_reset_template_success_html", "password_reset_success.html"
  202. )
  203. registration_template_success_html = email_config.get(
  204. "registration_template_success_html", "registration_success.html"
  205. )
  206. add_threepid_template_success_html = email_config.get(
  207. "add_threepid_template_success_html", "add_threepid_success.html"
  208. )
  209. # Read all templates from disk
  210. (
  211. self.email_password_reset_template_html,
  212. self.email_password_reset_template_text,
  213. self.email_registration_template_html,
  214. self.email_registration_template_text,
  215. self.email_add_threepid_template_html,
  216. self.email_add_threepid_template_text,
  217. self.email_password_reset_template_confirmation_html,
  218. self.email_password_reset_template_failure_html,
  219. self.email_registration_template_failure_html,
  220. self.email_add_threepid_template_failure_html,
  221. password_reset_template_success_html_template,
  222. registration_template_success_html_template,
  223. add_threepid_template_success_html_template,
  224. ) = self.read_templates(
  225. [
  226. password_reset_template_html,
  227. password_reset_template_text,
  228. registration_template_html,
  229. registration_template_text,
  230. add_threepid_template_html,
  231. add_threepid_template_text,
  232. "password_reset_confirmation.html",
  233. password_reset_template_failure_html,
  234. registration_template_failure_html,
  235. add_threepid_template_failure_html,
  236. password_reset_template_success_html,
  237. registration_template_success_html,
  238. add_threepid_template_success_html,
  239. ],
  240. (
  241. td
  242. for td in (
  243. self.root.server.custom_template_directory,
  244. template_dir,
  245. )
  246. if td
  247. ), # Filter out template_dir if not provided
  248. )
  249. # Render templates that do not contain any placeholders
  250. self.email_password_reset_template_success_html_content = (
  251. password_reset_template_success_html_template.render()
  252. )
  253. self.email_registration_template_success_html_content = (
  254. registration_template_success_html_template.render()
  255. )
  256. self.email_add_threepid_template_success_html_content = (
  257. add_threepid_template_success_html_template.render()
  258. )
  259. if self.email_enable_notifs:
  260. missing = []
  261. if not self.email_notif_from:
  262. missing.append("email.notif_from")
  263. if config.get("public_baseurl") is None:
  264. missing.append("public_baseurl")
  265. if missing:
  266. raise ConfigError(
  267. "email.enable_notifs is True but required keys are missing: %s"
  268. % (", ".join(missing),)
  269. )
  270. notif_template_html = email_config.get(
  271. "notif_template_html", "notif_mail.html"
  272. )
  273. notif_template_text = email_config.get(
  274. "notif_template_text", "notif_mail.txt"
  275. )
  276. (
  277. self.email_notif_template_html,
  278. self.email_notif_template_text,
  279. ) = self.read_templates(
  280. [notif_template_html, notif_template_text],
  281. (
  282. td
  283. for td in (
  284. self.root.server.custom_template_directory,
  285. template_dir,
  286. )
  287. if td
  288. ), # Filter out template_dir if not provided
  289. )
  290. self.email_notif_for_new_users = email_config.get(
  291. "notif_for_new_users", True
  292. )
  293. self.email_riot_base_url = email_config.get(
  294. "client_base_url", email_config.get("riot_base_url", None)
  295. )
  296. if self.root.account_validity.account_validity_renew_by_email_enabled:
  297. expiry_template_html = email_config.get(
  298. "expiry_template_html", "notice_expiry.html"
  299. )
  300. expiry_template_text = email_config.get(
  301. "expiry_template_text", "notice_expiry.txt"
  302. )
  303. (
  304. self.account_validity_template_html,
  305. self.account_validity_template_text,
  306. ) = self.read_templates(
  307. [expiry_template_html, expiry_template_text],
  308. (
  309. td
  310. for td in (
  311. self.root.server.custom_template_directory,
  312. template_dir,
  313. )
  314. if td
  315. ), # Filter out template_dir if not provided
  316. )
  317. subjects_config = email_config.get("subjects", {})
  318. subjects = {}
  319. for key, default in DEFAULT_SUBJECTS.items():
  320. subjects[key] = subjects_config.get(key, default)
  321. self.email_subjects = EmailSubjectConfig(**subjects)
  322. # The invite client location should be a HTTP(S) URL or None.
  323. self.invite_client_location = email_config.get("invite_client_location") or None
  324. if self.invite_client_location:
  325. if not isinstance(self.invite_client_location, str):
  326. raise ConfigError(
  327. "Config option email.invite_client_location must be type str"
  328. )
  329. if not (
  330. self.invite_client_location.startswith("http://")
  331. or self.invite_client_location.startswith("https://")
  332. ):
  333. raise ConfigError(
  334. "Config option email.invite_client_location must be a http or https URL",
  335. path=("email", "invite_client_location"),
  336. )
  337. def generate_config_section(self, config_dir_path, server_name, **kwargs):
  338. return (
  339. """\
  340. # Configuration for sending emails from Synapse.
  341. #
  342. # Server admins can configure custom templates for email content. See
  343. # https://matrix-org.github.io/synapse/latest/templates.html for more information.
  344. #
  345. email:
  346. # The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.
  347. #
  348. #smtp_host: mail.server
  349. # The port on the mail server for outgoing SMTP. Defaults to 25.
  350. #
  351. #smtp_port: 587
  352. # Username/password for authentication to the SMTP server. By default, no
  353. # authentication is attempted.
  354. #
  355. #smtp_user: "exampleusername"
  356. #smtp_pass: "examplepassword"
  357. # Uncomment the following to require TLS transport security for SMTP.
  358. # By default, Synapse will connect over plain text, and will then switch to
  359. # TLS via STARTTLS *if the SMTP server supports it*. If this option is set,
  360. # Synapse will refuse to connect unless the server supports STARTTLS.
  361. #
  362. #require_transport_security: true
  363. # Uncomment the following to disable TLS for SMTP.
  364. #
  365. # By default, if the server supports TLS, it will be used, and the server
  366. # must present a certificate that is valid for 'smtp_host'. If this option
  367. # is set to false, TLS will not be used.
  368. #
  369. #enable_tls: false
  370. # notif_from defines the "From" address to use when sending emails.
  371. # It must be set if email sending is enabled.
  372. #
  373. # The placeholder '%%(app)s' will be replaced by the application name,
  374. # which is normally 'app_name' (below), but may be overridden by the
  375. # Matrix client application.
  376. #
  377. # Note that the placeholder must be written '%%(app)s', including the
  378. # trailing 's'.
  379. #
  380. #notif_from: "Your Friendly %%(app)s homeserver <noreply@example.com>"
  381. # app_name defines the default value for '%%(app)s' in notif_from and email
  382. # subjects. It defaults to 'Matrix'.
  383. #
  384. #app_name: my_branded_matrix_server
  385. # Uncomment the following to enable sending emails for messages that the user
  386. # has missed. Disabled by default.
  387. #
  388. #enable_notifs: true
  389. # Uncomment the following to disable automatic subscription to email
  390. # notifications for new users. Enabled by default.
  391. #
  392. #notif_for_new_users: false
  393. # Custom URL for client links within the email notifications. By default
  394. # links will be based on "https://matrix.to".
  395. #
  396. # (This setting used to be called riot_base_url; the old name is still
  397. # supported for backwards-compatibility but is now deprecated.)
  398. #
  399. #client_base_url: "http://localhost/riot"
  400. # Configure the time that a validation email will expire after sending.
  401. # Defaults to 1h.
  402. #
  403. #validation_token_lifetime: 15m
  404. # The web client location to direct users to during an invite. This is passed
  405. # to the identity server as the org.matrix.web_client_location key. Defaults
  406. # to unset, giving no guidance to the identity server.
  407. #
  408. #invite_client_location: https://app.element.io
  409. # Subjects to use when sending emails from Synapse.
  410. #
  411. # The placeholder '%%(app)s' will be replaced with the value of the 'app_name'
  412. # setting above, or by a value dictated by the Matrix client application.
  413. #
  414. # If a subject isn't overridden in this configuration file, the value used as
  415. # its example will be used.
  416. #
  417. #subjects:
  418. # Subjects for notification emails.
  419. #
  420. # On top of the '%%(app)s' placeholder, these can use the following
  421. # placeholders:
  422. #
  423. # * '%%(person)s', which will be replaced by the display name of the user(s)
  424. # that sent the message(s), e.g. "Alice and Bob".
  425. # * '%%(room)s', which will be replaced by the name of the room the
  426. # message(s) have been sent to, e.g. "My super room".
  427. #
  428. # See the example provided for each setting to see which placeholder can be
  429. # used and how to use them.
  430. #
  431. # Subject to use to notify about one message from one or more user(s) in a
  432. # room which has a name.
  433. #message_from_person_in_room: "%(message_from_person_in_room)s"
  434. #
  435. # Subject to use to notify about one message from one or more user(s) in a
  436. # room which doesn't have a name.
  437. #message_from_person: "%(message_from_person)s"
  438. #
  439. # Subject to use to notify about multiple messages from one or more users in
  440. # a room which doesn't have a name.
  441. #messages_from_person: "%(messages_from_person)s"
  442. #
  443. # Subject to use to notify about multiple messages in a room which has a
  444. # name.
  445. #messages_in_room: "%(messages_in_room)s"
  446. #
  447. # Subject to use to notify about multiple messages in multiple rooms.
  448. #messages_in_room_and_others: "%(messages_in_room_and_others)s"
  449. #
  450. # Subject to use to notify about multiple messages from multiple persons in
  451. # multiple rooms. This is similar to the setting above except it's used when
  452. # the room in which the notification was triggered has no name.
  453. #messages_from_person_and_others: "%(messages_from_person_and_others)s"
  454. #
  455. # Subject to use to notify about an invite to a room which has a name.
  456. #invite_from_person_to_room: "%(invite_from_person_to_room)s"
  457. #
  458. # Subject to use to notify about an invite to a room which doesn't have a
  459. # name.
  460. #invite_from_person: "%(invite_from_person)s"
  461. # Subject for emails related to account administration.
  462. #
  463. # On top of the '%%(app)s' placeholder, these one can use the
  464. # '%%(server_name)s' placeholder, which will be replaced by the value of the
  465. # 'server_name' setting in your Synapse configuration.
  466. #
  467. # Subject to use when sending a password reset email.
  468. #password_reset: "%(password_reset)s"
  469. #
  470. # Subject to use when sending a verification email to assert an address's
  471. # ownership.
  472. #email_validation: "%(email_validation)s"
  473. """
  474. % DEFAULT_SUBJECTS
  475. )
  476. class ThreepidBehaviour(Enum):
  477. """
  478. Enum to define the behaviour of Synapse with regards to when it contacts an identity
  479. server for 3pid registration and password resets
  480. REMOTE = use an external server to send tokens
  481. LOCAL = send tokens ourselves
  482. OFF = disable registration via 3pid and password resets
  483. """
  484. REMOTE = "remote"
  485. LOCAL = "local"
  486. OFF = "off"