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.
 
 
 
 
 
 

490 lines
18 KiB

  1. # Copyright 2018 New Vector
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import email.message
  15. import os
  16. from typing import Any, Dict, List, Sequence, Tuple
  17. import attr
  18. import pkg_resources
  19. from twisted.internet.defer import Deferred
  20. from twisted.test.proto_helpers import MemoryReactor
  21. import synapse.rest.admin
  22. from synapse.api.errors import Codes, SynapseError
  23. from synapse.push.emailpusher import EmailPusher
  24. from synapse.rest.client import login, room
  25. from synapse.server import HomeServer
  26. from synapse.util import Clock
  27. from tests.unittest import HomeserverTestCase
  28. @attr.s(auto_attribs=True)
  29. class _User:
  30. "Helper wrapper for user ID and access token"
  31. id: str
  32. token: str
  33. class EmailPusherTests(HomeserverTestCase):
  34. servlets = [
  35. synapse.rest.admin.register_servlets_for_client_rest_resource,
  36. room.register_servlets,
  37. login.register_servlets,
  38. ]
  39. hijack_auth = False
  40. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  41. config = self.default_config()
  42. config["email"] = {
  43. "enable_notifs": True,
  44. "template_dir": os.path.abspath(
  45. pkg_resources.resource_filename("synapse", "res/templates")
  46. ),
  47. "expiry_template_html": "notice_expiry.html",
  48. "expiry_template_text": "notice_expiry.txt",
  49. "notif_template_html": "notif_mail.html",
  50. "notif_template_text": "notif_mail.txt",
  51. "smtp_host": "127.0.0.1",
  52. "smtp_port": 20,
  53. "require_transport_security": False,
  54. "smtp_user": None,
  55. "smtp_pass": None,
  56. "app_name": "Matrix",
  57. "notif_from": "test@example.com",
  58. "riot_base_url": None,
  59. }
  60. config["public_baseurl"] = "http://aaa"
  61. hs = self.setup_test_homeserver(config=config)
  62. # List[Tuple[Deferred, args, kwargs]]
  63. self.email_attempts: List[Tuple[Deferred, Sequence, Dict]] = []
  64. def sendmail(*args: Any, **kwargs: Any) -> Deferred:
  65. # This mocks out synapse.reactor.send_email._sendmail.
  66. d: Deferred = Deferred()
  67. self.email_attempts.append((d, args, kwargs))
  68. return d
  69. hs.get_send_email_handler()._sendmail = sendmail # type: ignore[assignment]
  70. return hs
  71. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  72. # Register the user who gets notified
  73. self.user_id = self.register_user("user", "pass")
  74. self.access_token = self.login("user", "pass")
  75. # Register other users
  76. self.others = [
  77. _User(
  78. id=self.register_user("otheruser1", "pass"),
  79. token=self.login("otheruser1", "pass"),
  80. ),
  81. _User(
  82. id=self.register_user("otheruser2", "pass"),
  83. token=self.login("otheruser2", "pass"),
  84. ),
  85. ]
  86. # Register the pusher
  87. user_tuple = self.get_success(
  88. self.hs.get_datastores().main.get_user_by_access_token(self.access_token)
  89. )
  90. assert user_tuple is not None
  91. self.token_id = user_tuple.token_id
  92. # We need to add email to account before we can create a pusher.
  93. self.get_success(
  94. hs.get_datastores().main.user_add_threepid(
  95. self.user_id, "email", "a@example.com", 0, 0
  96. )
  97. )
  98. pusher = self.get_success(
  99. self.hs.get_pusherpool().add_or_update_pusher(
  100. user_id=self.user_id,
  101. access_token=self.token_id,
  102. kind="email",
  103. app_id="m.email",
  104. app_display_name="Email Notifications",
  105. device_display_name="a@example.com",
  106. pushkey="a@example.com",
  107. lang=None,
  108. data={},
  109. )
  110. )
  111. assert isinstance(pusher, EmailPusher)
  112. self.pusher = pusher
  113. self.auth_handler = hs.get_auth_handler()
  114. self.store = hs.get_datastores().main
  115. def test_need_validated_email(self) -> None:
  116. """Test that we can only add an email pusher if the user has validated
  117. their email.
  118. """
  119. with self.assertRaises(SynapseError) as cm:
  120. self.get_success_or_raise(
  121. self.hs.get_pusherpool().add_or_update_pusher(
  122. user_id=self.user_id,
  123. access_token=self.token_id,
  124. kind="email",
  125. app_id="m.email",
  126. app_display_name="Email Notifications",
  127. device_display_name="b@example.com",
  128. pushkey="b@example.com",
  129. lang=None,
  130. data={},
  131. )
  132. )
  133. self.assertEqual(400, cm.exception.code)
  134. self.assertEqual(Codes.THREEPID_NOT_FOUND, cm.exception.errcode)
  135. def test_simple_sends_email(self) -> None:
  136. # Create a simple room with two users
  137. room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  138. self.helper.invite(
  139. room=room, src=self.user_id, tok=self.access_token, targ=self.others[0].id
  140. )
  141. self.helper.join(room=room, user=self.others[0].id, tok=self.others[0].token)
  142. # The other user sends a single message.
  143. self.helper.send(room, body="Hi!", tok=self.others[0].token)
  144. # We should get emailed about that message
  145. self._check_for_mail()
  146. # The other user sends multiple messages.
  147. self.helper.send(room, body="Hi!", tok=self.others[0].token)
  148. self.helper.send(room, body="There!", tok=self.others[0].token)
  149. self._check_for_mail()
  150. def test_invite_sends_email(self) -> None:
  151. # Create a room and invite the user to it
  152. room = self.helper.create_room_as(self.others[0].id, tok=self.others[0].token)
  153. self.helper.invite(
  154. room=room,
  155. src=self.others[0].id,
  156. tok=self.others[0].token,
  157. targ=self.user_id,
  158. )
  159. # We should get emailed about the invite
  160. self._check_for_mail()
  161. def test_invite_to_empty_room_sends_email(self) -> None:
  162. # Create a room and invite the user to it
  163. room = self.helper.create_room_as(self.others[0].id, tok=self.others[0].token)
  164. self.helper.invite(
  165. room=room,
  166. src=self.others[0].id,
  167. tok=self.others[0].token,
  168. targ=self.user_id,
  169. )
  170. # Then have the original user leave
  171. self.helper.leave(room, self.others[0].id, tok=self.others[0].token)
  172. # We should get emailed about the invite
  173. self._check_for_mail()
  174. def test_multiple_members_email(self) -> None:
  175. # We want to test multiple notifications, so we pause processing of push
  176. # while we send messages.
  177. self.pusher._pause_processing()
  178. # Create a simple room with multiple other users
  179. room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  180. for other in self.others:
  181. self.helper.invite(
  182. room=room, src=self.user_id, tok=self.access_token, targ=other.id
  183. )
  184. self.helper.join(room=room, user=other.id, tok=other.token)
  185. # The other users send some messages
  186. self.helper.send(room, body="Hi!", tok=self.others[0].token)
  187. self.helper.send(room, body="There!", tok=self.others[1].token)
  188. self.helper.send(room, body="There!", tok=self.others[1].token)
  189. # Nothing should have happened yet, as we're paused.
  190. assert not self.email_attempts
  191. self.pusher._resume_processing()
  192. # We should get emailed about those messages
  193. self._check_for_mail()
  194. def test_multiple_rooms(self) -> None:
  195. # We want to test multiple notifications from multiple rooms, so we pause
  196. # processing of push while we send messages.
  197. self.pusher._pause_processing()
  198. # Create a simple room with multiple other users
  199. rooms = [
  200. self.helper.create_room_as(self.user_id, tok=self.access_token),
  201. self.helper.create_room_as(self.user_id, tok=self.access_token),
  202. ]
  203. for r, other in zip(rooms, self.others):
  204. self.helper.invite(
  205. room=r, src=self.user_id, tok=self.access_token, targ=other.id
  206. )
  207. self.helper.join(room=r, user=other.id, tok=other.token)
  208. # The other users send some messages
  209. self.helper.send(rooms[0], body="Hi!", tok=self.others[0].token)
  210. self.helper.send(rooms[1], body="There!", tok=self.others[1].token)
  211. self.helper.send(rooms[1], body="There!", tok=self.others[1].token)
  212. # Nothing should have happened yet, as we're paused.
  213. assert not self.email_attempts
  214. self.pusher._resume_processing()
  215. # We should get emailed about those messages
  216. self._check_for_mail()
  217. def test_room_notifications_include_avatar(self) -> None:
  218. # Create a room and set its avatar.
  219. room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  220. self.helper.send_state(
  221. room, "m.room.avatar", {"url": "mxc://DUMMY_MEDIA_ID"}, self.access_token
  222. )
  223. # Invite two other uses.
  224. for other in self.others:
  225. self.helper.invite(
  226. room=room, src=self.user_id, tok=self.access_token, targ=other.id
  227. )
  228. self.helper.join(room=room, user=other.id, tok=other.token)
  229. # The other users send some messages.
  230. # TODO It seems that two messages are required to trigger an email?
  231. self.helper.send(room, body="Alpha", tok=self.others[0].token)
  232. self.helper.send(room, body="Beta", tok=self.others[1].token)
  233. # We should get emailed about those messages
  234. args, kwargs = self._check_for_mail()
  235. # That email should contain the room's avatar
  236. msg: bytes = args[5]
  237. # Multipart: plain text, base 64 encoded; html, base 64 encoded
  238. html = (
  239. email.message_from_bytes(msg)
  240. .get_payload()[1]
  241. .get_payload(decode=True)
  242. .decode()
  243. )
  244. self.assertIn("_matrix/media/v1/thumbnail/DUMMY_MEDIA_ID", html)
  245. def test_empty_room(self) -> None:
  246. """All users leaving a room shouldn't cause the pusher to break."""
  247. # Create a simple room with two users
  248. room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  249. self.helper.invite(
  250. room=room, src=self.user_id, tok=self.access_token, targ=self.others[0].id
  251. )
  252. self.helper.join(room=room, user=self.others[0].id, tok=self.others[0].token)
  253. # The other user sends a single message.
  254. self.helper.send(room, body="Hi!", tok=self.others[0].token)
  255. # Leave the room before the message is processed.
  256. self.helper.leave(room, self.user_id, tok=self.access_token)
  257. self.helper.leave(room, self.others[0].id, tok=self.others[0].token)
  258. # We should get emailed about that message
  259. self._check_for_mail()
  260. def test_empty_room_multiple_messages(self) -> None:
  261. """All users leaving a room shouldn't cause the pusher to break."""
  262. # Create a simple room with two users
  263. room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  264. self.helper.invite(
  265. room=room, src=self.user_id, tok=self.access_token, targ=self.others[0].id
  266. )
  267. self.helper.join(room=room, user=self.others[0].id, tok=self.others[0].token)
  268. # The other user sends a single message.
  269. self.helper.send(room, body="Hi!", tok=self.others[0].token)
  270. self.helper.send(room, body="There!", tok=self.others[0].token)
  271. # Leave the room before the message is processed.
  272. self.helper.leave(room, self.user_id, tok=self.access_token)
  273. self.helper.leave(room, self.others[0].id, tok=self.others[0].token)
  274. # We should get emailed about that message
  275. self._check_for_mail()
  276. def test_encrypted_message(self) -> None:
  277. room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  278. self.helper.invite(
  279. room=room, src=self.user_id, tok=self.access_token, targ=self.others[0].id
  280. )
  281. self.helper.join(room=room, user=self.others[0].id, tok=self.others[0].token)
  282. # The other user sends some messages
  283. self.helper.send_event(room, "m.room.encrypted", {}, tok=self.others[0].token)
  284. # We should get emailed about that message
  285. self._check_for_mail()
  286. def test_no_email_sent_after_removed(self) -> None:
  287. # Create a simple room with two users
  288. room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  289. self.helper.invite(
  290. room=room,
  291. src=self.user_id,
  292. tok=self.access_token,
  293. targ=self.others[0].id,
  294. )
  295. self.helper.join(
  296. room=room,
  297. user=self.others[0].id,
  298. tok=self.others[0].token,
  299. )
  300. # The other user sends a single message.
  301. self.helper.send(room, body="Hi!", tok=self.others[0].token)
  302. # We should get emailed about that message
  303. self._check_for_mail()
  304. # disassociate the user's email address
  305. self.get_success(
  306. self.auth_handler.delete_threepid(
  307. user_id=self.user_id,
  308. medium="email",
  309. address="a@example.com",
  310. )
  311. )
  312. # check that the pusher for that email address has been deleted
  313. pushers = list(
  314. self.get_success(
  315. self.hs.get_datastores().main.get_pushers_by(
  316. {"user_name": self.user_id}
  317. )
  318. )
  319. )
  320. self.assertEqual(len(pushers), 0)
  321. def test_remove_unlinked_pushers_background_job(self) -> None:
  322. """Checks that all existing pushers associated with unlinked email addresses are removed
  323. upon running the remove_deleted_email_pushers background update.
  324. """
  325. # disassociate the user's email address manually (without deleting the pusher).
  326. # This resembles the old behaviour, which the background update below is intended
  327. # to clean up.
  328. self.get_success(
  329. self.hs.get_datastores().main.user_delete_threepid(
  330. self.user_id, "email", "a@example.com"
  331. )
  332. )
  333. # Run the "remove_deleted_email_pushers" background job
  334. self.get_success(
  335. self.hs.get_datastores().main.db_pool.simple_insert(
  336. table="background_updates",
  337. values={
  338. "update_name": "remove_deleted_email_pushers",
  339. "progress_json": "{}",
  340. "depends_on": None,
  341. },
  342. )
  343. )
  344. # ... and tell the DataStore that it hasn't finished all updates yet
  345. self.hs.get_datastores().main.db_pool.updates._all_done = False
  346. # Now let's actually drive the updates to completion
  347. self.wait_for_background_updates()
  348. # Check that all pushers with unlinked addresses were deleted
  349. pushers = list(
  350. self.get_success(
  351. self.hs.get_datastores().main.get_pushers_by(
  352. {"user_name": self.user_id}
  353. )
  354. )
  355. )
  356. self.assertEqual(len(pushers), 0)
  357. def _check_for_mail(self) -> Tuple[Sequence, Dict]:
  358. """
  359. Assert that synapse sent off exactly one email notification.
  360. Returns:
  361. args and kwargs passed to synapse.reactor.send_email._sendmail for
  362. that notification.
  363. """
  364. # Get the stream ordering before it gets sent
  365. pushers = list(
  366. self.get_success(
  367. self.hs.get_datastores().main.get_pushers_by(
  368. {"user_name": self.user_id}
  369. )
  370. )
  371. )
  372. self.assertEqual(len(pushers), 1)
  373. last_stream_ordering = pushers[0].last_stream_ordering
  374. # Advance time a bit, so the pusher will register something has happened
  375. self.pump(10)
  376. # It hasn't succeeded yet, so the stream ordering shouldn't have moved
  377. pushers = list(
  378. self.get_success(
  379. self.hs.get_datastores().main.get_pushers_by(
  380. {"user_name": self.user_id}
  381. )
  382. )
  383. )
  384. self.assertEqual(len(pushers), 1)
  385. self.assertEqual(last_stream_ordering, pushers[0].last_stream_ordering)
  386. # One email was attempted to be sent
  387. self.assertEqual(len(self.email_attempts), 1)
  388. deferred, sendmail_args, sendmail_kwargs = self.email_attempts[0]
  389. # Make the email succeed
  390. deferred.callback(True)
  391. self.pump()
  392. # One email was attempted to be sent
  393. self.assertEqual(len(self.email_attempts), 1)
  394. # The stream ordering has increased
  395. pushers = list(
  396. self.get_success(
  397. self.hs.get_datastores().main.get_pushers_by(
  398. {"user_name": self.user_id}
  399. )
  400. )
  401. )
  402. self.assertEqual(len(pushers), 1)
  403. self.assertTrue(pushers[0].last_stream_ordering > last_stream_ordering)
  404. # Reset the attempts.
  405. self.email_attempts = []
  406. return sendmail_args, sendmail_kwargs