test_resource_limits_server_notices.py 16 KB

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