test_resource_limits_server_notices.py 15 KB

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