test_sync.py 12 KB

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