test_resource_limits_server_notices.py 17 KB

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