You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

405 lines
16 KiB

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