test_sync.py 34 KB

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