test_resource_limits_server_notices.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018, 2019 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from mock import Mock
  16. from twisted.internet import defer
  17. from synapse.api.constants import EventTypes, LimitBlockingTypes, ServerNoticeMsgType
  18. from synapse.api.errors import ResourceLimitError
  19. from synapse.rest import admin
  20. from synapse.rest.client.v1 import login, room
  21. from synapse.rest.client.v2_alpha import sync
  22. from synapse.server_notices.resource_limits_server_notices import (
  23. ResourceLimitsServerNotices,
  24. )
  25. from tests import unittest
  26. class TestResourceLimitsServerNotices(unittest.HomeserverTestCase):
  27. def make_homeserver(self, reactor, clock):
  28. hs_config = self.default_config()
  29. hs_config["server_notices"] = {
  30. "system_mxid_localpart": "server",
  31. "system_mxid_display_name": "test display name",
  32. "system_mxid_avatar_url": None,
  33. "room_name": "Server Notices",
  34. }
  35. hs = self.setup_test_homeserver(config=hs_config)
  36. return hs
  37. def prepare(self, reactor, clock, hs):
  38. self.server_notices_sender = self.hs.get_server_notices_sender()
  39. # relying on [1] is far from ideal, but the only case where
  40. # ResourceLimitsServerNotices class needs to be isolated is this test,
  41. # general code should never have a reason to do so ...
  42. self._rlsn = self.server_notices_sender._server_notices[1]
  43. if not isinstance(self._rlsn, ResourceLimitsServerNotices):
  44. raise Exception("Failed to find reference to ResourceLimitsServerNotices")
  45. self._rlsn._store.user_last_seen_monthly_active = Mock(
  46. return_value=defer.succeed(1000)
  47. )
  48. self._rlsn._server_notices_manager.send_notice = Mock(
  49. return_value=defer.succeed(Mock())
  50. )
  51. self._send_notice = self._rlsn._server_notices_manager.send_notice
  52. self.hs.config.limit_usage_by_mau = True
  53. self.user_id = "@user_id:test"
  54. self._rlsn._server_notices_manager.get_or_create_notice_room_for_user = Mock(
  55. return_value=defer.succeed("!something:localhost")
  56. )
  57. self._rlsn._store.add_tag_to_room = Mock(return_value=defer.succeed(None))
  58. self._rlsn._store.get_tags_for_room = Mock(return_value=defer.succeed({}))
  59. self.hs.config.admin_contact = "mailto:user@test.com"
  60. def test_maybe_send_server_notice_to_user_flag_off(self):
  61. """Tests cases where the flags indicate nothing to do"""
  62. # test hs disabled case
  63. self.hs.config.hs_disabled = True
  64. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  65. self._send_notice.assert_not_called()
  66. # Test when mau limiting disabled
  67. self.hs.config.hs_disabled = False
  68. self.hs.config.limit_usage_by_mau = False
  69. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  70. self._send_notice.assert_not_called()
  71. def test_maybe_send_server_notice_to_user_remove_blocked_notice(self):
  72. """Test when user has blocked notice, but should have it removed"""
  73. self._rlsn._auth.check_auth_blocking = Mock(return_value=defer.succeed(None))
  74. mock_event = Mock(
  75. type=EventTypes.Message, content={"msgtype": ServerNoticeMsgType}
  76. )
  77. self._rlsn._store.get_events = Mock(
  78. return_value=defer.succeed({"123": mock_event})
  79. )
  80. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  81. # Would be better to check the content, but once == remove blocking event
  82. self._send_notice.assert_called_once()
  83. def test_maybe_send_server_notice_to_user_remove_blocked_notice_noop(self):
  84. """
  85. Test when user has blocked notice, but notice ought to be there (NOOP)
  86. """
  87. self._rlsn._auth.check_auth_blocking = Mock(
  88. return_value=defer.succeed(None), side_effect=ResourceLimitError(403, "foo")
  89. )
  90. mock_event = Mock(
  91. type=EventTypes.Message, content={"msgtype": ServerNoticeMsgType}
  92. )
  93. self._rlsn._store.get_events = Mock(
  94. return_value=defer.succeed({"123": mock_event})
  95. )
  96. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  97. self._send_notice.assert_not_called()
  98. def test_maybe_send_server_notice_to_user_add_blocked_notice(self):
  99. """
  100. Test when user does not have blocked notice, but should have one
  101. """
  102. self._rlsn._auth.check_auth_blocking = Mock(
  103. return_value=defer.succeed(None), side_effect=ResourceLimitError(403, "foo")
  104. )
  105. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  106. # Would be better to check contents, but 2 calls == set blocking event
  107. self.assertEqual(self._send_notice.call_count, 2)
  108. def test_maybe_send_server_notice_to_user_add_blocked_notice_noop(self):
  109. """
  110. Test when user does not have blocked notice, nor should they (NOOP)
  111. """
  112. self._rlsn._auth.check_auth_blocking = Mock(return_value=defer.succeed(None))
  113. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  114. self._send_notice.assert_not_called()
  115. def test_maybe_send_server_notice_to_user_not_in_mau_cohort(self):
  116. """
  117. Test when user is not part of the MAU cohort - this should not ever
  118. happen - but ...
  119. """
  120. self._rlsn._auth.check_auth_blocking = Mock(return_value=defer.succeed(None))
  121. self._rlsn._store.user_last_seen_monthly_active = Mock(
  122. return_value=defer.succeed(None)
  123. )
  124. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  125. self._send_notice.assert_not_called()
  126. def test_maybe_send_server_notice_when_alerting_suppressed_room_unblocked(self):
  127. """
  128. Test that when server is over MAU limit and alerting is suppressed, then
  129. an alert message is not sent into the room
  130. """
  131. self.hs.config.mau_limit_alerting = False
  132. self._rlsn._auth.check_auth_blocking = Mock(
  133. return_value=defer.succeed(None),
  134. side_effect=ResourceLimitError(
  135. 403, "foo", limit_type=LimitBlockingTypes.MONTHLY_ACTIVE_USER
  136. ),
  137. )
  138. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  139. self.assertEqual(self._send_notice.call_count, 0)
  140. def test_check_hs_disabled_unaffected_by_mau_alert_suppression(self):
  141. """
  142. Test that when a server is disabled, that MAU limit alerting is ignored.
  143. """
  144. self.hs.config.mau_limit_alerting = False
  145. self._rlsn._auth.check_auth_blocking = Mock(
  146. return_value=defer.succeed(None),
  147. side_effect=ResourceLimitError(
  148. 403, "foo", limit_type=LimitBlockingTypes.HS_DISABLED
  149. ),
  150. )
  151. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  152. # Would be better to check contents, but 2 calls == set blocking event
  153. self.assertEqual(self._send_notice.call_count, 2)
  154. def test_maybe_send_server_notice_when_alerting_suppressed_room_blocked(self):
  155. """
  156. When the room is already in a blocked state, test that when alerting
  157. is suppressed that the room is returned to an unblocked state.
  158. """
  159. self.hs.config.mau_limit_alerting = False
  160. self._rlsn._auth.check_auth_blocking = Mock(
  161. return_value=defer.succeed(None),
  162. side_effect=ResourceLimitError(
  163. 403, "foo", limit_type=LimitBlockingTypes.MONTHLY_ACTIVE_USER
  164. ),
  165. )
  166. self._rlsn._server_notices_manager.__is_room_currently_blocked = Mock(
  167. return_value=defer.succeed((True, []))
  168. )
  169. mock_event = Mock(
  170. type=EventTypes.Message, content={"msgtype": ServerNoticeMsgType}
  171. )
  172. self._rlsn._store.get_events = Mock(
  173. return_value=defer.succeed({"123": mock_event})
  174. )
  175. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  176. self._send_notice.assert_called_once()
  177. class TestResourceLimitsServerNoticesWithRealRooms(unittest.HomeserverTestCase):
  178. servlets = [
  179. admin.register_servlets,
  180. login.register_servlets,
  181. room.register_servlets,
  182. sync.register_servlets,
  183. ]
  184. def default_config(self):
  185. c = super().default_config()
  186. c["server_notices"] = {
  187. "system_mxid_localpart": "server",
  188. "system_mxid_display_name": None,
  189. "system_mxid_avatar_url": None,
  190. "room_name": "Test Server Notice Room",
  191. }
  192. c["limit_usage_by_mau"] = True
  193. c["max_mau_value"] = 5
  194. c["admin_contact"] = "mailto:user@test.com"
  195. return c
  196. def prepare(self, reactor, clock, hs):
  197. self.store = self.hs.get_datastore()
  198. self.server_notices_sender = self.hs.get_server_notices_sender()
  199. self.server_notices_manager = self.hs.get_server_notices_manager()
  200. self.event_source = self.hs.get_event_sources()
  201. # relying on [1] is far from ideal, but the only case where
  202. # ResourceLimitsServerNotices class needs to be isolated is this test,
  203. # general code should never have a reason to do so ...
  204. self._rlsn = self.server_notices_sender._server_notices[1]
  205. if not isinstance(self._rlsn, ResourceLimitsServerNotices):
  206. raise Exception("Failed to find reference to ResourceLimitsServerNotices")
  207. self.user_id = "@user_id:test"
  208. def test_server_notice_only_sent_once(self):
  209. self.store.get_monthly_active_count = Mock(return_value=1000)
  210. self.store.user_last_seen_monthly_active = Mock(
  211. return_value=defer.succeed(1000)
  212. )
  213. # Call the function multiple times to ensure we only send the notice once
  214. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  215. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  216. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  217. # Now lets get the last load of messages in the service notice room and
  218. # check that there is only one server notice
  219. room_id = self.get_success(
  220. self.server_notices_manager.get_or_create_notice_room_for_user(self.user_id)
  221. )
  222. token = self.get_success(self.event_source.get_current_token())
  223. events, _ = self.get_success(
  224. self.store.get_recent_events_for_room(
  225. room_id, limit=100, end_token=token.room_key
  226. )
  227. )
  228. count = 0
  229. for event in events:
  230. if event.type != EventTypes.Message:
  231. continue
  232. if event.content.get("msgtype") != ServerNoticeMsgType:
  233. continue
  234. count += 1
  235. self.assertEqual(count, 1)
  236. def test_no_invite_without_notice(self):
  237. """Tests that a user doesn't get invited to a server notices room without a
  238. server notice being sent.
  239. The scenario for this test is a single user on a server where the MAU limit
  240. hasn't been reached (since it's the only user and the limit is 5), so users
  241. shouldn't receive a server notice.
  242. """
  243. self.register_user("user", "password")
  244. tok = self.login("user", "password")
  245. request, channel = self.make_request("GET", "/sync?timeout=0", access_token=tok)
  246. self.render(request)
  247. invites = channel.json_body["rooms"]["invite"]
  248. self.assertEqual(len(invites), 0, invites)
  249. def test_invite_with_notice(self):
  250. """Tests that, if the MAU limit is hit, the server notices user invites each user
  251. to a room in which it has sent a notice.
  252. """
  253. user_id, tok, room_id = self._trigger_notice_and_join()
  254. # Sync again to retrieve the events in the room, so we can check whether this
  255. # room has a notice in it.
  256. request, channel = self.make_request("GET", "/sync?timeout=0", access_token=tok)
  257. self.render(request)
  258. # Scan the events in the room to search for a message from the server notices
  259. # user.
  260. events = channel.json_body["rooms"]["join"][room_id]["timeline"]["events"]
  261. notice_in_room = False
  262. for event in events:
  263. if (
  264. event["type"] == EventTypes.Message
  265. and event["sender"] == self.hs.config.server_notices_mxid
  266. ):
  267. notice_in_room = True
  268. self.assertTrue(notice_in_room, "No server notice in room")
  269. def _trigger_notice_and_join(self):
  270. """Creates enough active users to hit the MAU limit and trigger a system notice
  271. about it, then joins the system notices room with one of the users created.
  272. Returns:
  273. user_id (str): The ID of the user that joined the room.
  274. tok (str): The access token of the user that joined the room.
  275. room_id (str): The ID of the room that's been joined.
  276. """
  277. user_id = None
  278. tok = None
  279. invites = []
  280. # Register as many users as the MAU limit allows.
  281. for i in range(self.hs.config.max_mau_value):
  282. localpart = "user%d" % i
  283. user_id = self.register_user(localpart, "password")
  284. tok = self.login(localpart, "password")
  285. # Sync with the user's token to mark the user as active.
  286. request, channel = self.make_request(
  287. "GET", "/sync?timeout=0", access_token=tok,
  288. )
  289. self.render(request)
  290. # Also retrieves the list of invites for this user. We don't care about that
  291. # one except if we're processing the last user, which should have received an
  292. # invite to a room with a server notice about the MAU limit being reached.
  293. # We could also pick another user and sync with it, which would return an
  294. # invite to a system notices room, but it doesn't matter which user we're
  295. # using so we use the last one because it saves us an extra sync.
  296. invites = channel.json_body["rooms"]["invite"]
  297. # Make sure we have an invite to process.
  298. self.assertEqual(len(invites), 1, invites)
  299. # Join the room.
  300. room_id = list(invites.keys())[0]
  301. self.helper.join(room=room_id, user=user_id, tok=tok)
  302. return user_id, tok, room_id