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.
 
 
 
 
 
 

822 lines
29 KiB

  1. # Copyright 2018-2019 New Vector Ltd
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. from typing import List
  17. from parameterized import parameterized
  18. from twisted.test.proto_helpers import MemoryReactor
  19. import synapse.rest.admin
  20. from synapse.api.constants import (
  21. EventContentFields,
  22. EventTypes,
  23. ReceiptTypes,
  24. RelationTypes,
  25. )
  26. from synapse.rest.client import devices, knock, login, read_marker, receipts, room, sync
  27. from synapse.server import HomeServer
  28. from synapse.types import JsonDict
  29. from synapse.util import Clock
  30. from tests import unittest
  31. from tests.federation.transport.test_knocking import (
  32. KnockingStrippedStateEventHelperMixin,
  33. )
  34. from tests.server import TimedOutException
  35. class FilterTestCase(unittest.HomeserverTestCase):
  36. user_id = "@apple:test"
  37. servlets = [
  38. synapse.rest.admin.register_servlets_for_client_rest_resource,
  39. room.register_servlets,
  40. login.register_servlets,
  41. sync.register_servlets,
  42. ]
  43. def test_sync_argless(self) -> None:
  44. channel = self.make_request("GET", "/sync")
  45. self.assertEqual(channel.code, 200)
  46. self.assertIn("next_batch", channel.json_body)
  47. class SyncFilterTestCase(unittest.HomeserverTestCase):
  48. servlets = [
  49. synapse.rest.admin.register_servlets_for_client_rest_resource,
  50. room.register_servlets,
  51. login.register_servlets,
  52. sync.register_servlets,
  53. ]
  54. def test_sync_filter_labels(self) -> None:
  55. """Test that we can filter by a label."""
  56. sync_filter = json.dumps(
  57. {
  58. "room": {
  59. "timeline": {
  60. "types": [EventTypes.Message],
  61. "org.matrix.labels": ["#fun"],
  62. }
  63. }
  64. }
  65. )
  66. events = self._test_sync_filter_labels(sync_filter)
  67. self.assertEqual(len(events), 2, [event["content"] for event in events])
  68. self.assertEqual(events[0]["content"]["body"], "with right label", events[0])
  69. self.assertEqual(events[1]["content"]["body"], "with right label", events[1])
  70. def test_sync_filter_not_labels(self) -> None:
  71. """Test that we can filter by the absence of a label."""
  72. sync_filter = json.dumps(
  73. {
  74. "room": {
  75. "timeline": {
  76. "types": [EventTypes.Message],
  77. "org.matrix.not_labels": ["#fun"],
  78. }
  79. }
  80. }
  81. )
  82. events = self._test_sync_filter_labels(sync_filter)
  83. self.assertEqual(len(events), 3, [event["content"] for event in events])
  84. self.assertEqual(events[0]["content"]["body"], "without label", events[0])
  85. self.assertEqual(events[1]["content"]["body"], "with wrong label", events[1])
  86. self.assertEqual(
  87. events[2]["content"]["body"], "with two wrong labels", events[2]
  88. )
  89. def test_sync_filter_labels_not_labels(self) -> None:
  90. """Test that we can filter by both a label and the absence of another label."""
  91. sync_filter = json.dumps(
  92. {
  93. "room": {
  94. "timeline": {
  95. "types": [EventTypes.Message],
  96. "org.matrix.labels": ["#work"],
  97. "org.matrix.not_labels": ["#notfun"],
  98. }
  99. }
  100. }
  101. )
  102. events = self._test_sync_filter_labels(sync_filter)
  103. self.assertEqual(len(events), 1, [event["content"] for event in events])
  104. self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0])
  105. def _test_sync_filter_labels(self, sync_filter: str) -> List[JsonDict]:
  106. user_id = self.register_user("kermit", "test")
  107. tok = self.login("kermit", "test")
  108. room_id = self.helper.create_room_as(user_id, tok=tok)
  109. self.helper.send_event(
  110. room_id=room_id,
  111. type=EventTypes.Message,
  112. content={
  113. "msgtype": "m.text",
  114. "body": "with right label",
  115. EventContentFields.LABELS: ["#fun"],
  116. },
  117. tok=tok,
  118. )
  119. self.helper.send_event(
  120. room_id=room_id,
  121. type=EventTypes.Message,
  122. content={"msgtype": "m.text", "body": "without label"},
  123. tok=tok,
  124. )
  125. self.helper.send_event(
  126. room_id=room_id,
  127. type=EventTypes.Message,
  128. content={
  129. "msgtype": "m.text",
  130. "body": "with wrong label",
  131. EventContentFields.LABELS: ["#work"],
  132. },
  133. tok=tok,
  134. )
  135. self.helper.send_event(
  136. room_id=room_id,
  137. type=EventTypes.Message,
  138. content={
  139. "msgtype": "m.text",
  140. "body": "with two wrong labels",
  141. EventContentFields.LABELS: ["#work", "#notfun"],
  142. },
  143. tok=tok,
  144. )
  145. self.helper.send_event(
  146. room_id=room_id,
  147. type=EventTypes.Message,
  148. content={
  149. "msgtype": "m.text",
  150. "body": "with right label",
  151. EventContentFields.LABELS: ["#fun"],
  152. },
  153. tok=tok,
  154. )
  155. channel = self.make_request(
  156. "GET", "/sync?filter=%s" % sync_filter, access_token=tok
  157. )
  158. self.assertEqual(channel.code, 200, channel.result)
  159. return channel.json_body["rooms"]["join"][room_id]["timeline"]["events"]
  160. class SyncTypingTests(unittest.HomeserverTestCase):
  161. servlets = [
  162. synapse.rest.admin.register_servlets_for_client_rest_resource,
  163. room.register_servlets,
  164. login.register_servlets,
  165. sync.register_servlets,
  166. ]
  167. user_id = True
  168. hijack_auth = False
  169. def test_sync_backwards_typing(self) -> None:
  170. """
  171. If the typing serial goes backwards and the typing handler is then reset
  172. (such as when the master restarts and sets the typing serial to 0), we
  173. do not incorrectly return typing information that had a serial greater
  174. than the now-reset serial.
  175. """
  176. typing_url = "/rooms/%s/typing/%s?access_token=%s"
  177. sync_url = "/sync?timeout=3000000&access_token=%s&since=%s"
  178. # Register the user who gets notified
  179. user_id = self.register_user("user", "pass")
  180. access_token = self.login("user", "pass")
  181. # Register the user who sends the message
  182. other_user_id = self.register_user("otheruser", "pass")
  183. other_access_token = self.login("otheruser", "pass")
  184. # Create a room
  185. room = self.helper.create_room_as(user_id, tok=access_token)
  186. # Invite the other person
  187. self.helper.invite(room=room, src=user_id, tok=access_token, targ=other_user_id)
  188. # The other user joins
  189. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  190. # The other user sends some messages
  191. self.helper.send(room, body="Hi!", tok=other_access_token)
  192. self.helper.send(room, body="There!", tok=other_access_token)
  193. # Start typing.
  194. channel = self.make_request(
  195. "PUT",
  196. typing_url % (room, other_user_id, other_access_token),
  197. b'{"typing": true, "timeout": 30000}',
  198. )
  199. self.assertEqual(200, channel.code)
  200. channel = self.make_request("GET", "/sync?access_token=%s" % (access_token,))
  201. self.assertEqual(200, channel.code)
  202. next_batch = channel.json_body["next_batch"]
  203. # Stop typing.
  204. channel = self.make_request(
  205. "PUT",
  206. typing_url % (room, other_user_id, other_access_token),
  207. b'{"typing": false}',
  208. )
  209. self.assertEqual(200, channel.code)
  210. # Start typing.
  211. channel = self.make_request(
  212. "PUT",
  213. typing_url % (room, other_user_id, other_access_token),
  214. b'{"typing": true, "timeout": 30000}',
  215. )
  216. self.assertEqual(200, channel.code)
  217. # Should return immediately
  218. channel = self.make_request("GET", sync_url % (access_token, next_batch))
  219. self.assertEqual(200, channel.code)
  220. next_batch = channel.json_body["next_batch"]
  221. # Reset typing serial back to 0, as if the master had.
  222. typing = self.hs.get_typing_handler()
  223. typing._latest_room_serial = 0
  224. # Since it checks the state token, we need some state to update to
  225. # invalidate the stream token.
  226. self.helper.send(room, body="There!", tok=other_access_token)
  227. channel = self.make_request("GET", sync_url % (access_token, next_batch))
  228. self.assertEqual(200, channel.code)
  229. next_batch = channel.json_body["next_batch"]
  230. # This should time out! But it does not, because our stream token is
  231. # ahead, and therefore it's saying the typing (that we've actually
  232. # already seen) is new, since it's got a token above our new, now-reset
  233. # stream token.
  234. channel = self.make_request("GET", sync_url % (access_token, next_batch))
  235. self.assertEqual(200, channel.code)
  236. next_batch = channel.json_body["next_batch"]
  237. # Clear the typing information, so that it doesn't think everything is
  238. # in the future.
  239. typing._reset()
  240. # Now it SHOULD fail as it never completes!
  241. with self.assertRaises(TimedOutException):
  242. self.make_request("GET", sync_url % (access_token, next_batch))
  243. class SyncKnockTestCase(KnockingStrippedStateEventHelperMixin):
  244. servlets = [
  245. synapse.rest.admin.register_servlets,
  246. login.register_servlets,
  247. room.register_servlets,
  248. sync.register_servlets,
  249. knock.register_servlets,
  250. ]
  251. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  252. self.store = hs.get_datastores().main
  253. self.url = "/sync?since=%s"
  254. self.next_batch = "s0"
  255. # Register the first user (used to create the room to knock on).
  256. self.user_id = self.register_user("kermit", "monkey")
  257. self.tok = self.login("kermit", "monkey")
  258. # Create the room we'll knock on.
  259. self.room_id = self.helper.create_room_as(
  260. self.user_id,
  261. is_public=False,
  262. room_version="7",
  263. tok=self.tok,
  264. )
  265. # Register the second user (used to knock on the room).
  266. self.knocker = self.register_user("knocker", "monkey")
  267. self.knocker_tok = self.login("knocker", "monkey")
  268. # Perform an initial sync for the knocking user.
  269. channel = self.make_request(
  270. "GET",
  271. self.url % self.next_batch,
  272. access_token=self.tok,
  273. )
  274. self.assertEqual(channel.code, 200, channel.json_body)
  275. # Store the next batch for the next request.
  276. self.next_batch = channel.json_body["next_batch"]
  277. # Set up some room state to test with.
  278. self.expected_room_state = self.send_example_state_events_to_room(
  279. hs, self.room_id, self.user_id
  280. )
  281. def test_knock_room_state(self) -> None:
  282. """Tests that /sync returns state from a room after knocking on it."""
  283. # Knock on a room
  284. channel = self.make_request(
  285. "POST",
  286. f"/_matrix/client/r0/knock/{self.room_id}",
  287. b"{}",
  288. self.knocker_tok,
  289. )
  290. self.assertEqual(200, channel.code, channel.result)
  291. # We expect to see the knock event in the stripped room state later
  292. self.expected_room_state[EventTypes.Member] = {
  293. "content": {"membership": "knock", "displayname": "knocker"},
  294. "state_key": "@knocker:test",
  295. }
  296. # Check that /sync includes stripped state from the room
  297. channel = self.make_request(
  298. "GET",
  299. self.url % self.next_batch,
  300. access_token=self.knocker_tok,
  301. )
  302. self.assertEqual(channel.code, 200, channel.json_body)
  303. # Extract the stripped room state events from /sync
  304. knock_entry = channel.json_body["rooms"]["knock"]
  305. room_state_events = knock_entry[self.room_id]["knock_state"]["events"]
  306. # Validate that the knock membership event came last
  307. self.assertEqual(room_state_events[-1]["type"], EventTypes.Member)
  308. # Validate the stripped room state events
  309. self.check_knock_room_state_against_room_state(
  310. room_state_events, self.expected_room_state
  311. )
  312. class UnreadMessagesTestCase(unittest.HomeserverTestCase):
  313. servlets = [
  314. synapse.rest.admin.register_servlets,
  315. login.register_servlets,
  316. read_marker.register_servlets,
  317. room.register_servlets,
  318. sync.register_servlets,
  319. receipts.register_servlets,
  320. ]
  321. def default_config(self) -> JsonDict:
  322. config = super().default_config()
  323. config["experimental_features"] = {
  324. "msc2654_enabled": True,
  325. }
  326. return config
  327. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  328. self.url = "/sync?since=%s"
  329. self.next_batch = "s0"
  330. # Register the first user (used to check the unread counts).
  331. self.user_id = self.register_user("kermit", "monkey")
  332. self.tok = self.login("kermit", "monkey")
  333. # Create the room we'll check unread counts for.
  334. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  335. # Register the second user (used to send events to the room).
  336. self.user2 = self.register_user("kermit2", "monkey")
  337. self.tok2 = self.login("kermit2", "monkey")
  338. # Change the power levels of the room so that the second user can send state
  339. # events.
  340. self.helper.send_state(
  341. self.room_id,
  342. EventTypes.PowerLevels,
  343. {
  344. "users": {self.user_id: 100, self.user2: 100},
  345. "users_default": 0,
  346. "events": {
  347. "m.room.name": 50,
  348. "m.room.power_levels": 100,
  349. "m.room.history_visibility": 100,
  350. "m.room.canonical_alias": 50,
  351. "m.room.avatar": 50,
  352. "m.room.tombstone": 100,
  353. "m.room.server_acl": 100,
  354. "m.room.encryption": 100,
  355. },
  356. "events_default": 0,
  357. "state_default": 50,
  358. "ban": 50,
  359. "kick": 50,
  360. "redact": 50,
  361. "invite": 0,
  362. },
  363. tok=self.tok,
  364. )
  365. def test_unread_counts(self) -> None:
  366. """Tests that /sync returns the right value for the unread count (MSC2654)."""
  367. # Check that our own messages don't increase the unread count.
  368. self.helper.send(self.room_id, "hello", tok=self.tok)
  369. self._check_unread_count(0)
  370. # Join the new user and check that this doesn't increase the unread count.
  371. self.helper.join(room=self.room_id, user=self.user2, tok=self.tok2)
  372. self._check_unread_count(0)
  373. # Check that the new user sending a message increases our unread count.
  374. res = self.helper.send(self.room_id, "hello", tok=self.tok2)
  375. self._check_unread_count(1)
  376. # Send a read receipt to tell the server we've read the latest event.
  377. channel = self.make_request(
  378. "POST",
  379. f"/rooms/{self.room_id}/read_markers",
  380. {ReceiptTypes.READ: res["event_id"]},
  381. access_token=self.tok,
  382. )
  383. self.assertEqual(channel.code, 200, channel.json_body)
  384. # Check that the unread counter is back to 0.
  385. self._check_unread_count(0)
  386. # Check that private read receipts don't break unread counts
  387. res = self.helper.send(self.room_id, "hello", tok=self.tok2)
  388. self._check_unread_count(1)
  389. # Send a read receipt to tell the server we've read the latest event.
  390. channel = self.make_request(
  391. "POST",
  392. f"/rooms/{self.room_id}/receipt/{ReceiptTypes.READ_PRIVATE}/{res['event_id']}",
  393. {},
  394. access_token=self.tok,
  395. )
  396. self.assertEqual(channel.code, 200, channel.json_body)
  397. # Check that the unread counter is back to 0.
  398. self._check_unread_count(0)
  399. # Check that room name changes increase the unread counter.
  400. self.helper.send_state(
  401. self.room_id,
  402. "m.room.name",
  403. {"name": "my super room"},
  404. tok=self.tok2,
  405. )
  406. self._check_unread_count(1)
  407. # Check that room topic changes increase the unread counter.
  408. self.helper.send_state(
  409. self.room_id,
  410. "m.room.topic",
  411. {"topic": "welcome!!!"},
  412. tok=self.tok2,
  413. )
  414. self._check_unread_count(2)
  415. # Check that encrypted messages increase the unread counter.
  416. self.helper.send_event(self.room_id, EventTypes.Encrypted, {}, tok=self.tok2)
  417. self._check_unread_count(3)
  418. # Check that custom events with a body increase the unread counter.
  419. result = self.helper.send_event(
  420. self.room_id,
  421. "org.matrix.custom_type",
  422. {"body": "hello"},
  423. tok=self.tok2,
  424. )
  425. event_id = result["event_id"]
  426. self._check_unread_count(4)
  427. # Check that edits don't increase the unread counter.
  428. self.helper.send_event(
  429. room_id=self.room_id,
  430. type=EventTypes.Message,
  431. content={
  432. "body": "hello",
  433. "msgtype": "m.text",
  434. "m.relates_to": {
  435. "rel_type": RelationTypes.REPLACE,
  436. "event_id": event_id,
  437. },
  438. },
  439. tok=self.tok2,
  440. )
  441. self._check_unread_count(4)
  442. # Check that notices don't increase the unread counter.
  443. self.helper.send_event(
  444. room_id=self.room_id,
  445. type=EventTypes.Message,
  446. content={"body": "hello", "msgtype": "m.notice"},
  447. tok=self.tok2,
  448. )
  449. self._check_unread_count(4)
  450. # Check that tombstone events changes increase the unread counter.
  451. res1 = self.helper.send_state(
  452. self.room_id,
  453. EventTypes.Tombstone,
  454. {"replacement_room": "!someroom:test"},
  455. tok=self.tok2,
  456. )
  457. self._check_unread_count(5)
  458. res2 = self.helper.send(self.room_id, "hello", tok=self.tok2)
  459. # Make sure both m.read and m.read.private advance
  460. channel = self.make_request(
  461. "POST",
  462. f"/rooms/{self.room_id}/receipt/m.read/{res1['event_id']}",
  463. {},
  464. access_token=self.tok,
  465. )
  466. self.assertEqual(channel.code, 200, channel.json_body)
  467. self._check_unread_count(1)
  468. channel = self.make_request(
  469. "POST",
  470. f"/rooms/{self.room_id}/receipt/{ReceiptTypes.READ_PRIVATE}/{res2['event_id']}",
  471. {},
  472. access_token=self.tok,
  473. )
  474. self.assertEqual(channel.code, 200, channel.json_body)
  475. self._check_unread_count(0)
  476. # We test for all three receipt types that influence notification counts
  477. @parameterized.expand(
  478. [
  479. ReceiptTypes.READ,
  480. ReceiptTypes.READ_PRIVATE,
  481. ]
  482. )
  483. def test_read_receipts_only_go_down(self, receipt_type: str) -> None:
  484. # Join the new user
  485. self.helper.join(room=self.room_id, user=self.user2, tok=self.tok2)
  486. # Send messages
  487. res1 = self.helper.send(self.room_id, "hello", tok=self.tok2)
  488. res2 = self.helper.send(self.room_id, "hello", tok=self.tok2)
  489. # Read last event
  490. channel = self.make_request(
  491. "POST",
  492. f"/rooms/{self.room_id}/receipt/{ReceiptTypes.READ_PRIVATE}/{res2['event_id']}",
  493. {},
  494. access_token=self.tok,
  495. )
  496. self.assertEqual(channel.code, 200, channel.json_body)
  497. self._check_unread_count(0)
  498. # Make sure neither m.read nor m.read.private make the
  499. # read receipt go up to an older event
  500. channel = self.make_request(
  501. "POST",
  502. f"/rooms/{self.room_id}/receipt/{ReceiptTypes.READ_PRIVATE}/{res1['event_id']}",
  503. {},
  504. access_token=self.tok,
  505. )
  506. self.assertEqual(channel.code, 200, channel.json_body)
  507. self._check_unread_count(0)
  508. channel = self.make_request(
  509. "POST",
  510. f"/rooms/{self.room_id}/receipt/m.read/{res1['event_id']}",
  511. {},
  512. access_token=self.tok,
  513. )
  514. self.assertEqual(channel.code, 200, channel.json_body)
  515. self._check_unread_count(0)
  516. def _check_unread_count(self, expected_count: int) -> None:
  517. """Syncs and compares the unread count with the expected value."""
  518. channel = self.make_request(
  519. "GET",
  520. self.url % self.next_batch,
  521. access_token=self.tok,
  522. )
  523. self.assertEqual(channel.code, 200, channel.json_body)
  524. room_entry = (
  525. channel.json_body.get("rooms", {}).get("join", {}).get(self.room_id, {})
  526. )
  527. self.assertEqual(
  528. room_entry.get("org.matrix.msc2654.unread_count", 0),
  529. expected_count,
  530. room_entry,
  531. )
  532. # Store the next batch for the next request.
  533. self.next_batch = channel.json_body["next_batch"]
  534. class SyncCacheTestCase(unittest.HomeserverTestCase):
  535. servlets = [
  536. synapse.rest.admin.register_servlets,
  537. login.register_servlets,
  538. sync.register_servlets,
  539. ]
  540. def test_noop_sync_does_not_tightloop(self) -> None:
  541. """If the sync times out, we shouldn't cache the result
  542. Essentially a regression test for https://github.com/matrix-org/synapse/issues/8518.
  543. """
  544. self.user_id = self.register_user("kermit", "monkey")
  545. self.tok = self.login("kermit", "monkey")
  546. # we should immediately get an initial sync response
  547. channel = self.make_request("GET", "/sync", access_token=self.tok)
  548. self.assertEqual(channel.code, 200, channel.json_body)
  549. # now, make an incremental sync request, with a timeout
  550. next_batch = channel.json_body["next_batch"]
  551. channel = self.make_request(
  552. "GET",
  553. f"/sync?since={next_batch}&timeout=10000",
  554. access_token=self.tok,
  555. await_result=False,
  556. )
  557. # that should block for 10 seconds
  558. with self.assertRaises(TimedOutException):
  559. channel.await_result(timeout_ms=9900)
  560. channel.await_result(timeout_ms=200)
  561. self.assertEqual(channel.code, 200, channel.json_body)
  562. # we expect the next_batch in the result to be the same as before
  563. self.assertEqual(channel.json_body["next_batch"], next_batch)
  564. # another incremental sync should also block.
  565. channel = self.make_request(
  566. "GET",
  567. f"/sync?since={next_batch}&timeout=10000",
  568. access_token=self.tok,
  569. await_result=False,
  570. )
  571. # that should block for 10 seconds
  572. with self.assertRaises(TimedOutException):
  573. channel.await_result(timeout_ms=9900)
  574. channel.await_result(timeout_ms=200)
  575. self.assertEqual(channel.code, 200, channel.json_body)
  576. class DeviceListSyncTestCase(unittest.HomeserverTestCase):
  577. servlets = [
  578. synapse.rest.admin.register_servlets,
  579. login.register_servlets,
  580. sync.register_servlets,
  581. devices.register_servlets,
  582. ]
  583. def test_user_with_no_rooms_receives_self_device_list_updates(self) -> None:
  584. """Tests that a user with no rooms still receives their own device list updates"""
  585. device_id = "TESTDEVICE"
  586. # Register a user and login, creating a device
  587. self.user_id = self.register_user("kermit", "monkey")
  588. self.tok = self.login("kermit", "monkey", device_id=device_id)
  589. # Request an initial sync
  590. channel = self.make_request("GET", "/sync", access_token=self.tok)
  591. self.assertEqual(channel.code, 200, channel.json_body)
  592. next_batch = channel.json_body["next_batch"]
  593. # Now, make an incremental sync request.
  594. # It won't return until something has happened
  595. incremental_sync_channel = self.make_request(
  596. "GET",
  597. f"/sync?since={next_batch}&timeout=30000",
  598. access_token=self.tok,
  599. await_result=False,
  600. )
  601. # Change our device's display name
  602. channel = self.make_request(
  603. "PUT",
  604. f"devices/{device_id}",
  605. {
  606. "display_name": "freeze ray",
  607. },
  608. access_token=self.tok,
  609. )
  610. self.assertEqual(channel.code, 200, channel.json_body)
  611. # The sync should now have returned
  612. incremental_sync_channel.await_result(timeout_ms=20000)
  613. self.assertEqual(incremental_sync_channel.code, 200, channel.json_body)
  614. # We should have received notification that the (user's) device has changed
  615. device_list_changes = incremental_sync_channel.json_body.get(
  616. "device_lists", {}
  617. ).get("changed", [])
  618. self.assertIn(
  619. self.user_id, device_list_changes, incremental_sync_channel.json_body
  620. )
  621. class ExcludeRoomTestCase(unittest.HomeserverTestCase):
  622. servlets = [
  623. synapse.rest.admin.register_servlets,
  624. login.register_servlets,
  625. sync.register_servlets,
  626. room.register_servlets,
  627. ]
  628. def prepare(
  629. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  630. ) -> None:
  631. self.user_id = self.register_user("user", "password")
  632. self.tok = self.login("user", "password")
  633. self.excluded_room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  634. self.included_room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  635. # We need to manually append the room ID, because we can't know the ID before
  636. # creating the room, and we can't set the config after starting the homeserver.
  637. self.hs.get_sync_handler().rooms_to_exclude_globally.append(
  638. self.excluded_room_id
  639. )
  640. def test_join_leave(self) -> None:
  641. """Tests that rooms are correctly excluded from the 'join' and 'leave' sections of
  642. sync responses.
  643. """
  644. channel = self.make_request("GET", "/sync", access_token=self.tok)
  645. self.assertEqual(channel.code, 200, channel.result)
  646. self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["join"])
  647. self.assertIn(self.included_room_id, channel.json_body["rooms"]["join"])
  648. self.helper.leave(self.excluded_room_id, self.user_id, tok=self.tok)
  649. self.helper.leave(self.included_room_id, self.user_id, tok=self.tok)
  650. channel = self.make_request(
  651. "GET",
  652. "/sync?since=" + channel.json_body["next_batch"],
  653. access_token=self.tok,
  654. )
  655. self.assertEqual(channel.code, 200, channel.result)
  656. self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["leave"])
  657. self.assertIn(self.included_room_id, channel.json_body["rooms"]["leave"])
  658. def test_invite(self) -> None:
  659. """Tests that rooms are correctly excluded from the 'invite' section of sync
  660. responses.
  661. """
  662. invitee = self.register_user("invitee", "password")
  663. invitee_tok = self.login("invitee", "password")
  664. self.helper.invite(self.excluded_room_id, self.user_id, invitee, tok=self.tok)
  665. self.helper.invite(self.included_room_id, self.user_id, invitee, tok=self.tok)
  666. channel = self.make_request("GET", "/sync", access_token=invitee_tok)
  667. self.assertEqual(channel.code, 200, channel.result)
  668. self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["invite"])
  669. self.assertIn(self.included_room_id, channel.json_body["rooms"]["invite"])
  670. def test_incremental_sync(self) -> None:
  671. """Tests that activity in the room is properly filtered out of incremental
  672. syncs.
  673. """
  674. channel = self.make_request("GET", "/sync", access_token=self.tok)
  675. self.assertEqual(channel.code, 200, channel.result)
  676. next_batch = channel.json_body["next_batch"]
  677. self.helper.send(self.excluded_room_id, tok=self.tok)
  678. self.helper.send(self.included_room_id, tok=self.tok)
  679. channel = self.make_request(
  680. "GET",
  681. f"/sync?since={next_batch}",
  682. access_token=self.tok,
  683. )
  684. self.assertEqual(channel.code, 200, channel.result)
  685. self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["join"])
  686. self.assertIn(self.included_room_id, channel.json_body["rooms"]["join"])