test_sync.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # Copyright 2018 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 Optional
  15. from unittest.mock import MagicMock, Mock, patch
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.api.constants import EventTypes, JoinRules
  18. from synapse.api.errors import Codes, ResourceLimitError
  19. from synapse.api.filtering import Filtering
  20. from synapse.api.room_versions import RoomVersions
  21. from synapse.handlers.sync import SyncConfig, SyncResult
  22. from synapse.rest import admin
  23. from synapse.rest.client import knock, login, room
  24. from synapse.server import HomeServer
  25. from synapse.types import UserID, create_requester
  26. from synapse.util import Clock
  27. import tests.unittest
  28. import tests.utils
  29. from tests.test_utils import make_awaitable
  30. class SyncTestCase(tests.unittest.HomeserverTestCase):
  31. """Tests Sync Handler."""
  32. servlets = [
  33. admin.register_servlets,
  34. knock.register_servlets,
  35. login.register_servlets,
  36. room.register_servlets,
  37. ]
  38. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  39. self.sync_handler = self.hs.get_sync_handler()
  40. self.store = self.hs.get_datastores().main
  41. # AuthBlocking reads from the hs' config on initialization. We need to
  42. # modify its config instead of the hs'
  43. self.auth_blocking = self.hs.get_auth_blocking()
  44. def test_wait_for_sync_for_user_auth_blocking(self) -> None:
  45. user_id1 = "@user1:test"
  46. user_id2 = "@user2:test"
  47. sync_config = generate_sync_config(user_id1)
  48. requester = create_requester(user_id1)
  49. self.reactor.advance(100) # So we get not 0 time
  50. self.auth_blocking._limit_usage_by_mau = True
  51. self.auth_blocking._max_mau_value = 1
  52. # Check that the happy case does not throw errors
  53. self.get_success(self.store.upsert_monthly_active_user(user_id1))
  54. self.get_success(
  55. self.sync_handler.wait_for_sync_for_user(requester, sync_config)
  56. )
  57. # Test that global lock works
  58. self.auth_blocking._hs_disabled = True
  59. e = self.get_failure(
  60. self.sync_handler.wait_for_sync_for_user(requester, sync_config),
  61. ResourceLimitError,
  62. )
  63. self.assertEqual(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  64. self.auth_blocking._hs_disabled = False
  65. sync_config = generate_sync_config(user_id2)
  66. requester = create_requester(user_id2)
  67. e = self.get_failure(
  68. self.sync_handler.wait_for_sync_for_user(requester, sync_config),
  69. ResourceLimitError,
  70. )
  71. self.assertEqual(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  72. def test_unknown_room_version(self) -> None:
  73. """
  74. A room with an unknown room version should not break sync (and should be excluded).
  75. """
  76. inviter = self.register_user("creator", "pass", admin=True)
  77. inviter_tok = self.login("@creator:test", "pass")
  78. user = self.register_user("user", "pass")
  79. tok = self.login("user", "pass")
  80. # Do an initial sync on a different device.
  81. requester = create_requester(user)
  82. initial_result = self.get_success(
  83. self.sync_handler.wait_for_sync_for_user(
  84. requester, sync_config=generate_sync_config(user, device_id="dev")
  85. )
  86. )
  87. # Create a room as the user.
  88. joined_room = self.helper.create_room_as(user, tok=tok)
  89. # Invite the user to the room as someone else.
  90. invite_room = self.helper.create_room_as(inviter, tok=inviter_tok)
  91. self.helper.invite(invite_room, targ=user, tok=inviter_tok)
  92. knock_room = self.helper.create_room_as(
  93. inviter, room_version=RoomVersions.V7.identifier, tok=inviter_tok
  94. )
  95. self.helper.send_state(
  96. knock_room,
  97. EventTypes.JoinRules,
  98. {"join_rule": JoinRules.KNOCK},
  99. tok=inviter_tok,
  100. )
  101. channel = self.make_request(
  102. "POST",
  103. "/_matrix/client/r0/knock/%s" % (knock_room,),
  104. b"{}",
  105. tok,
  106. )
  107. self.assertEqual(200, channel.code, channel.result)
  108. # The rooms should appear in the sync response.
  109. result = self.get_success(
  110. self.sync_handler.wait_for_sync_for_user(
  111. requester, sync_config=generate_sync_config(user)
  112. )
  113. )
  114. self.assertIn(joined_room, [r.room_id for r in result.joined])
  115. self.assertIn(invite_room, [r.room_id for r in result.invited])
  116. self.assertIn(knock_room, [r.room_id for r in result.knocked])
  117. # Test a incremental sync (by providing a since_token).
  118. result = self.get_success(
  119. self.sync_handler.wait_for_sync_for_user(
  120. requester,
  121. sync_config=generate_sync_config(user, device_id="dev"),
  122. since_token=initial_result.next_batch,
  123. )
  124. )
  125. self.assertIn(joined_room, [r.room_id for r in result.joined])
  126. self.assertIn(invite_room, [r.room_id for r in result.invited])
  127. self.assertIn(knock_room, [r.room_id for r in result.knocked])
  128. # Poke the database and update the room version to an unknown one.
  129. for room_id in (joined_room, invite_room, knock_room):
  130. self.get_success(
  131. self.hs.get_datastores().main.db_pool.simple_update(
  132. "rooms",
  133. keyvalues={"room_id": room_id},
  134. updatevalues={"room_version": "unknown-room-version"},
  135. desc="updated-room-version",
  136. )
  137. )
  138. # Blow away caches (supported room versions can only change due to a restart).
  139. self.store.get_rooms_for_user_with_stream_ordering.invalidate_all()
  140. self.store.get_rooms_for_user.invalidate_all()
  141. self.get_success(self.store._get_event_cache.clear())
  142. self.store._event_ref.clear()
  143. # The rooms should be excluded from the sync response.
  144. # Get a new request key.
  145. result = self.get_success(
  146. self.sync_handler.wait_for_sync_for_user(
  147. requester, sync_config=generate_sync_config(user)
  148. )
  149. )
  150. self.assertNotIn(joined_room, [r.room_id for r in result.joined])
  151. self.assertNotIn(invite_room, [r.room_id for r in result.invited])
  152. self.assertNotIn(knock_room, [r.room_id for r in result.knocked])
  153. # The rooms should also not be in an incremental sync.
  154. result = self.get_success(
  155. self.sync_handler.wait_for_sync_for_user(
  156. requester,
  157. sync_config=generate_sync_config(user, device_id="dev"),
  158. since_token=initial_result.next_batch,
  159. )
  160. )
  161. self.assertNotIn(joined_room, [r.room_id for r in result.joined])
  162. self.assertNotIn(invite_room, [r.room_id for r in result.invited])
  163. self.assertNotIn(knock_room, [r.room_id for r in result.knocked])
  164. def test_ban_wins_race_with_join(self) -> None:
  165. """Rooms shouldn't appear under "joined" if a join loses a race to a ban.
  166. A complicated edge case. Imagine the following scenario:
  167. * you attempt to join a room
  168. * racing with that is a ban which comes in over federation, which ends up with
  169. an earlier stream_ordering than the join.
  170. * you get a sync response with a sync token which is _after_ the ban, but before
  171. the join
  172. * now your join lands; it is a valid event because its `prev_event`s predate the
  173. ban, but will not make it into current_state_events (because bans win over
  174. joins in state res, essentially).
  175. * When we do a sync from the incremental sync, the only event in the timeline
  176. is your join ... and yet you aren't joined.
  177. The ban coming in over federation isn't crucial for this behaviour; the key
  178. requirements are:
  179. 1. the homeserver generates a join event with prev_events that precede the ban
  180. (so that it passes the "are you banned" test)
  181. 2. the join event has a stream_ordering after that of the ban.
  182. We use monkeypatching to artificially trigger condition (1).
  183. """
  184. # A local user Alice creates a room.
  185. owner = self.register_user("alice", "password")
  186. owner_tok = self.login(owner, "password")
  187. room_id = self.helper.create_room_as(owner, is_public=True, tok=owner_tok)
  188. # Do a sync as Alice to get the latest event in the room.
  189. alice_sync_result: SyncResult = self.get_success(
  190. self.sync_handler.wait_for_sync_for_user(
  191. create_requester(owner), generate_sync_config(owner)
  192. )
  193. )
  194. self.assertEqual(len(alice_sync_result.joined), 1)
  195. self.assertEqual(alice_sync_result.joined[0].room_id, room_id)
  196. last_room_creation_event_id = (
  197. alice_sync_result.joined[0].timeline.events[-1].event_id
  198. )
  199. # Eve, a ne'er-do-well, registers.
  200. eve = self.register_user("eve", "password")
  201. eve_token = self.login(eve, "password")
  202. # Alice preemptively bans Eve.
  203. self.helper.ban(room_id, owner, eve, tok=owner_tok)
  204. # Eve syncs.
  205. eve_requester = create_requester(eve)
  206. eve_sync_config = generate_sync_config(eve)
  207. eve_sync_after_ban: SyncResult = self.get_success(
  208. self.sync_handler.wait_for_sync_for_user(eve_requester, eve_sync_config)
  209. )
  210. # Sanity check this sync result. We shouldn't be joined to the room.
  211. self.assertEqual(eve_sync_after_ban.joined, [])
  212. # Eve tries to join the room. We monkey patch the internal logic which selects
  213. # the prev_events used when creating the join event, such that the ban does not
  214. # precede the join.
  215. mocked_get_prev_events = patch.object(
  216. self.hs.get_datastores().main,
  217. "get_prev_events_for_room",
  218. new_callable=MagicMock,
  219. return_value=make_awaitable([last_room_creation_event_id]),
  220. )
  221. with mocked_get_prev_events:
  222. self.helper.join(room_id, eve, tok=eve_token)
  223. # Eve makes a second, incremental sync.
  224. eve_incremental_sync_after_join: SyncResult = self.get_success(
  225. self.sync_handler.wait_for_sync_for_user(
  226. eve_requester,
  227. eve_sync_config,
  228. since_token=eve_sync_after_ban.next_batch,
  229. )
  230. )
  231. # Eve should not see herself as joined to the room.
  232. self.assertEqual(eve_incremental_sync_after_join.joined, [])
  233. # If we did a third initial sync, we should _still_ see eve is not joined to the room.
  234. eve_initial_sync_after_join: SyncResult = self.get_success(
  235. self.sync_handler.wait_for_sync_for_user(
  236. eve_requester,
  237. eve_sync_config,
  238. since_token=None,
  239. )
  240. )
  241. self.assertEqual(eve_initial_sync_after_join.joined, [])
  242. _request_key = 0
  243. def generate_sync_config(
  244. user_id: str, device_id: Optional[str] = "device_id"
  245. ) -> SyncConfig:
  246. """Generate a sync config (with a unique request key)."""
  247. global _request_key
  248. _request_key += 1
  249. return SyncConfig(
  250. user=UserID.from_string(user_id),
  251. filter_collection=Filtering(Mock()).DEFAULT_FILTER_COLLECTION,
  252. is_guest=False,
  253. request_key=("request_key", _request_key),
  254. device_id=device_id,
  255. )