You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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