test_resource_limits_server_notices.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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.server_notices.resource_limits_server_notices import (
  20. ResourceLimitsServerNotices,
  21. )
  22. from tests import unittest
  23. class TestResourceLimitsServerNotices(unittest.HomeserverTestCase):
  24. def make_homeserver(self, reactor, clock):
  25. hs_config = self.default_config("test")
  26. hs_config["server_notices"] = {
  27. "system_mxid_localpart": "server",
  28. "system_mxid_display_name": "test display name",
  29. "system_mxid_avatar_url": None,
  30. "room_name": "Server Notices",
  31. }
  32. hs = self.setup_test_homeserver(config=hs_config)
  33. return hs
  34. def prepare(self, reactor, clock, hs):
  35. self.server_notices_sender = self.hs.get_server_notices_sender()
  36. # relying on [1] is far from ideal, but the only case where
  37. # ResourceLimitsServerNotices class needs to be isolated is this test,
  38. # general code should never have a reason to do so ...
  39. self._rlsn = self.server_notices_sender._server_notices[1]
  40. if not isinstance(self._rlsn, ResourceLimitsServerNotices):
  41. raise Exception("Failed to find reference to ResourceLimitsServerNotices")
  42. self._rlsn._store.user_last_seen_monthly_active = Mock(
  43. return_value=defer.succeed(1000)
  44. )
  45. self._send_notice = self._rlsn._server_notices_manager.send_notice
  46. self._rlsn._server_notices_manager.send_notice = Mock()
  47. self._rlsn._state.get_current_state = Mock(return_value=defer.succeed(None))
  48. self._rlsn._store.get_events = Mock(return_value=defer.succeed({}))
  49. self._send_notice = self._rlsn._server_notices_manager.send_notice
  50. self.hs.config.limit_usage_by_mau = True
  51. self.user_id = "@user_id:test"
  52. # self.server_notices_mxid = "@server:test"
  53. # self.server_notices_mxid_display_name = None
  54. # self.server_notices_mxid_avatar_url = None
  55. # self.server_notices_room_name = "Server Notices"
  56. self._rlsn._server_notices_manager.get_notice_room_for_user = Mock(
  57. returnValue=""
  58. )
  59. self._rlsn._store.add_tag_to_room = Mock()
  60. self._rlsn._store.get_tags_for_room = Mock(return_value={})
  61. self.hs.config.admin_contact = "mailto:user@test.com"
  62. def test_maybe_send_server_notice_to_user_flag_off(self):
  63. """Tests cases where the flags indicate nothing to do"""
  64. # test hs disabled case
  65. self.hs.config.hs_disabled = True
  66. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  67. self._send_notice.assert_not_called()
  68. # Test when mau limiting disabled
  69. self.hs.config.hs_disabled = False
  70. self.hs.config.limit_usage_by_mau = False
  71. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  72. self._send_notice.assert_not_called()
  73. def test_maybe_send_server_notice_to_user_remove_blocked_notice(self):
  74. """Test when user has blocked notice, but should have it removed"""
  75. self._rlsn._auth.check_auth_blocking = Mock()
  76. mock_event = Mock(
  77. type=EventTypes.Message, content={"msgtype": ServerNoticeMsgType}
  78. )
  79. self._rlsn._store.get_events = Mock(
  80. return_value=defer.succeed({"123": mock_event})
  81. )
  82. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  83. # Would be better to check the content, but once == remove blocking event
  84. self._send_notice.assert_called_once()
  85. def test_maybe_send_server_notice_to_user_remove_blocked_notice_noop(self):
  86. """
  87. Test when user has blocked notice, but notice ought to be there (NOOP)
  88. """
  89. self._rlsn._auth.check_auth_blocking = Mock(
  90. side_effect=ResourceLimitError(403, "foo")
  91. )
  92. mock_event = Mock(
  93. type=EventTypes.Message, content={"msgtype": ServerNoticeMsgType}
  94. )
  95. self._rlsn._store.get_events = Mock(
  96. return_value=defer.succeed({"123": mock_event})
  97. )
  98. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  99. self._send_notice.assert_not_called()
  100. def test_maybe_send_server_notice_to_user_add_blocked_notice(self):
  101. """
  102. Test when user does not have blocked notice, but should have one
  103. """
  104. self._rlsn._auth.check_auth_blocking = Mock(
  105. side_effect=ResourceLimitError(403, "foo")
  106. )
  107. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  108. # Would be better to check contents, but 2 calls == set blocking event
  109. self.assertEqual(self._send_notice.call_count, 2)
  110. def test_maybe_send_server_notice_to_user_add_blocked_notice_noop(self):
  111. """
  112. Test when user does not have blocked notice, nor should they (NOOP)
  113. """
  114. self._rlsn._auth.check_auth_blocking = Mock()
  115. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  116. self._send_notice.assert_not_called()
  117. def test_maybe_send_server_notice_to_user_not_in_mau_cohort(self):
  118. """
  119. Test when user is not part of the MAU cohort - this should not ever
  120. happen - but ...
  121. """
  122. self._rlsn._auth.check_auth_blocking = Mock()
  123. self._rlsn._store.user_last_seen_monthly_active = Mock(
  124. return_value=defer.succeed(None)
  125. )
  126. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  127. self._send_notice.assert_not_called()
  128. def test_maybe_send_server_notice_when_alerting_suppressed_room_unblocked(self):
  129. """
  130. Test that when server is over MAU limit and alerting is suppressed, then
  131. an alert message is not sent into the room
  132. """
  133. self.hs.config.mau_limit_alerting = False
  134. self._rlsn._auth.check_auth_blocking = Mock(
  135. side_effect=ResourceLimitError(
  136. 403, "foo", limit_type=LimitBlockingTypes.MONTHLY_ACTIVE_USER
  137. )
  138. )
  139. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  140. self.assertTrue(self._send_notice.call_count == 0)
  141. def test_check_hs_disabled_unaffected_by_mau_alert_suppression(self):
  142. """
  143. Test that when a server is disabled, that MAU limit alerting is ignored.
  144. """
  145. self.hs.config.mau_limit_alerting = False
  146. self._rlsn._auth.check_auth_blocking = Mock(
  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. side_effect=ResourceLimitError(
  162. 403, "foo", limit_type=LimitBlockingTypes.MONTHLY_ACTIVE_USER
  163. )
  164. )
  165. self._rlsn._server_notices_manager.__is_room_currently_blocked = Mock(
  166. return_value=defer.succeed((True, []))
  167. )
  168. mock_event = Mock(
  169. type=EventTypes.Message, content={"msgtype": ServerNoticeMsgType}
  170. )
  171. self._rlsn._store.get_events = Mock(
  172. return_value=defer.succeed({"123": mock_event})
  173. )
  174. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  175. self._send_notice.assert_called_once()
  176. class TestResourceLimitsServerNoticesWithRealRooms(unittest.HomeserverTestCase):
  177. def prepare(self, reactor, clock, hs):
  178. self.store = self.hs.get_datastore()
  179. self.server_notices_sender = self.hs.get_server_notices_sender()
  180. self.server_notices_manager = self.hs.get_server_notices_manager()
  181. self.event_source = self.hs.get_event_sources()
  182. # relying on [1] is far from ideal, but the only case where
  183. # ResourceLimitsServerNotices class needs to be isolated is this test,
  184. # general code should never have a reason to do so ...
  185. self._rlsn = self.server_notices_sender._server_notices[1]
  186. if not isinstance(self._rlsn, ResourceLimitsServerNotices):
  187. raise Exception("Failed to find reference to ResourceLimitsServerNotices")
  188. self.hs.config.limit_usage_by_mau = True
  189. self.hs.config.hs_disabled = False
  190. self.hs.config.max_mau_value = 5
  191. self.hs.config.server_notices_mxid = "@server:test"
  192. self.hs.config.server_notices_mxid_display_name = None
  193. self.hs.config.server_notices_mxid_avatar_url = None
  194. self.hs.config.server_notices_room_name = "Test Server Notice Room"
  195. self.user_id = "@user_id:test"
  196. self.hs.config.admin_contact = "mailto:user@test.com"
  197. def test_server_notice_only_sent_once(self):
  198. self.store.get_monthly_active_count = Mock(return_value=1000)
  199. self.store.user_last_seen_monthly_active = Mock(return_value=1000)
  200. # Call the function multiple times to ensure we only send the notice once
  201. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  202. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  203. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  204. # Now lets get the last load of messages in the service notice room and
  205. # check that there is only one server notice
  206. room_id = self.get_success(
  207. self.server_notices_manager.get_notice_room_for_user(self.user_id)
  208. )
  209. token = self.get_success(self.event_source.get_current_token())
  210. events, _ = self.get_success(
  211. self.store.get_recent_events_for_room(
  212. room_id, limit=100, end_token=token.room_key
  213. )
  214. )
  215. count = 0
  216. for event in events:
  217. if event.type != EventTypes.Message:
  218. continue
  219. if event.content.get("msgtype") != ServerNoticeMsgType:
  220. continue
  221. count += 1
  222. self.assertEqual(count, 1)