test_resource_limits_server_notices.py 15 KB

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