test_sync.py 12 KB

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