test_resource_limits_server_notices.py 15 KB

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