test_sync.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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()._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_event_cache.clear()
  139. self.store._event_ref.clear()
  140. # The rooms should be excluded from the sync response.
  141. # Get a new request key.
  142. result = self.get_success(
  143. self.sync_handler.wait_for_sync_for_user(
  144. requester, sync_config=generate_sync_config(user)
  145. )
  146. )
  147. self.assertNotIn(joined_room, [r.room_id for r in result.joined])
  148. self.assertNotIn(invite_room, [r.room_id for r in result.invited])
  149. self.assertNotIn(knock_room, [r.room_id for r in result.knocked])
  150. # The rooms should also not be in an incremental sync.
  151. result = self.get_success(
  152. self.sync_handler.wait_for_sync_for_user(
  153. requester,
  154. sync_config=generate_sync_config(user, device_id="dev"),
  155. since_token=initial_result.next_batch,
  156. )
  157. )
  158. self.assertNotIn(joined_room, [r.room_id for r in result.joined])
  159. self.assertNotIn(invite_room, [r.room_id for r in result.invited])
  160. self.assertNotIn(knock_room, [r.room_id for r in result.knocked])
  161. def test_ban_wins_race_with_join(self):
  162. """Rooms shouldn't appear under "joined" if a join loses a race to a ban.
  163. A complicated edge case. Imagine the following scenario:
  164. * you attempt to join a room
  165. * racing with that is a ban which comes in over federation, which ends up with
  166. an earlier stream_ordering than the join.
  167. * you get a sync response with a sync token which is _after_ the ban, but before
  168. the join
  169. * now your join lands; it is a valid event because its `prev_event`s predate the
  170. ban, but will not make it into current_state_events (because bans win over
  171. joins in state res, essentially).
  172. * When we do a sync from the incremental sync, the only event in the timeline
  173. is your join ... and yet you aren't joined.
  174. The ban coming in over federation isn't crucial for this behaviour; the key
  175. requirements are:
  176. 1. the homeserver generates a join event with prev_events that precede the ban
  177. (so that it passes the "are you banned" test)
  178. 2. the join event has a stream_ordering after that of the ban.
  179. We use monkeypatching to artificially trigger condition (1).
  180. """
  181. # A local user Alice creates a room.
  182. owner = self.register_user("alice", "password")
  183. owner_tok = self.login(owner, "password")
  184. room_id = self.helper.create_room_as(owner, is_public=True, tok=owner_tok)
  185. # Do a sync as Alice to get the latest event in the room.
  186. alice_sync_result: SyncResult = self.get_success(
  187. self.sync_handler.wait_for_sync_for_user(
  188. create_requester(owner), generate_sync_config(owner)
  189. )
  190. )
  191. self.assertEqual(len(alice_sync_result.joined), 1)
  192. self.assertEqual(alice_sync_result.joined[0].room_id, room_id)
  193. last_room_creation_event_id = (
  194. alice_sync_result.joined[0].timeline.events[-1].event_id
  195. )
  196. # Eve, a ne'er-do-well, registers.
  197. eve = self.register_user("eve", "password")
  198. eve_token = self.login(eve, "password")
  199. # Alice preemptively bans Eve.
  200. self.helper.ban(room_id, owner, eve, tok=owner_tok)
  201. # Eve syncs.
  202. eve_requester = create_requester(eve)
  203. eve_sync_config = generate_sync_config(eve)
  204. eve_sync_after_ban: SyncResult = self.get_success(
  205. self.sync_handler.wait_for_sync_for_user(eve_requester, eve_sync_config)
  206. )
  207. # Sanity check this sync result. We shouldn't be joined to the room.
  208. self.assertEqual(eve_sync_after_ban.joined, [])
  209. # Eve tries to join the room. We monkey patch the internal logic which selects
  210. # the prev_events used when creating the join event, such that the ban does not
  211. # precede the join.
  212. mocked_get_prev_events = patch.object(
  213. self.hs.get_datastores().main,
  214. "get_prev_events_for_room",
  215. new_callable=MagicMock,
  216. return_value=make_awaitable([last_room_creation_event_id]),
  217. )
  218. with mocked_get_prev_events:
  219. self.helper.join(room_id, eve, tok=eve_token)
  220. # Eve makes a second, incremental sync.
  221. eve_incremental_sync_after_join: SyncResult = self.get_success(
  222. self.sync_handler.wait_for_sync_for_user(
  223. eve_requester,
  224. eve_sync_config,
  225. since_token=eve_sync_after_ban.next_batch,
  226. )
  227. )
  228. # Eve should not see herself as joined to the room.
  229. self.assertEqual(eve_incremental_sync_after_join.joined, [])
  230. # If we did a third initial sync, we should _still_ see eve is not joined to the room.
  231. eve_initial_sync_after_join: SyncResult = self.get_success(
  232. self.sync_handler.wait_for_sync_for_user(
  233. eve_requester,
  234. eve_sync_config,
  235. since_token=None,
  236. )
  237. )
  238. self.assertEqual(eve_initial_sync_after_join.joined, [])
  239. _request_key = 0
  240. def generate_sync_config(
  241. user_id: str, device_id: Optional[str] = "device_id"
  242. ) -> SyncConfig:
  243. """Generate a sync config (with a unique request key)."""
  244. global _request_key
  245. _request_key += 1
  246. return SyncConfig(
  247. user=UserID.from_string(user_id),
  248. filter_collection=Filtering(Mock()).DEFAULT_FILTER_COLLECTION,
  249. is_guest=False,
  250. request_key=("request_key", _request_key),
  251. device_id=device_id,
  252. )