test_sync.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. from tests.unittest import override_config
  38. class FilterTestCase(unittest.HomeserverTestCase):
  39. user_id = "@apple:test"
  40. servlets = [
  41. synapse.rest.admin.register_servlets_for_client_rest_resource,
  42. room.register_servlets,
  43. login.register_servlets,
  44. sync.register_servlets,
  45. ]
  46. def test_sync_argless(self) -> None:
  47. channel = self.make_request("GET", "/sync")
  48. self.assertEqual(channel.code, 200)
  49. self.assertIn("next_batch", channel.json_body)
  50. class SyncFilterTestCase(unittest.HomeserverTestCase):
  51. servlets = [
  52. synapse.rest.admin.register_servlets_for_client_rest_resource,
  53. room.register_servlets,
  54. login.register_servlets,
  55. sync.register_servlets,
  56. ]
  57. def test_sync_filter_labels(self) -> None:
  58. """Test that we can filter by a label."""
  59. sync_filter = json.dumps(
  60. {
  61. "room": {
  62. "timeline": {
  63. "types": [EventTypes.Message],
  64. "org.matrix.labels": ["#fun"],
  65. }
  66. }
  67. }
  68. )
  69. events = self._test_sync_filter_labels(sync_filter)
  70. self.assertEqual(len(events), 2, [event["content"] for event in events])
  71. self.assertEqual(events[0]["content"]["body"], "with right label", events[0])
  72. self.assertEqual(events[1]["content"]["body"], "with right label", events[1])
  73. def test_sync_filter_not_labels(self) -> None:
  74. """Test that we can filter by the absence of a label."""
  75. sync_filter = json.dumps(
  76. {
  77. "room": {
  78. "timeline": {
  79. "types": [EventTypes.Message],
  80. "org.matrix.not_labels": ["#fun"],
  81. }
  82. }
  83. }
  84. )
  85. events = self._test_sync_filter_labels(sync_filter)
  86. self.assertEqual(len(events), 3, [event["content"] for event in events])
  87. self.assertEqual(events[0]["content"]["body"], "without label", events[0])
  88. self.assertEqual(events[1]["content"]["body"], "with wrong label", events[1])
  89. self.assertEqual(
  90. events[2]["content"]["body"], "with two wrong labels", events[2]
  91. )
  92. def test_sync_filter_labels_not_labels(self) -> None:
  93. """Test that we can filter by both a label and the absence of another label."""
  94. sync_filter = json.dumps(
  95. {
  96. "room": {
  97. "timeline": {
  98. "types": [EventTypes.Message],
  99. "org.matrix.labels": ["#work"],
  100. "org.matrix.not_labels": ["#notfun"],
  101. }
  102. }
  103. }
  104. )
  105. events = self._test_sync_filter_labels(sync_filter)
  106. self.assertEqual(len(events), 1, [event["content"] for event in events])
  107. self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0])
  108. def _test_sync_filter_labels(self, sync_filter: str) -> List[JsonDict]:
  109. user_id = self.register_user("kermit", "test")
  110. tok = self.login("kermit", "test")
  111. room_id = self.helper.create_room_as(user_id, tok=tok)
  112. self.helper.send_event(
  113. room_id=room_id,
  114. type=EventTypes.Message,
  115. content={
  116. "msgtype": "m.text",
  117. "body": "with right label",
  118. EventContentFields.LABELS: ["#fun"],
  119. },
  120. tok=tok,
  121. )
  122. self.helper.send_event(
  123. room_id=room_id,
  124. type=EventTypes.Message,
  125. content={"msgtype": "m.text", "body": "without label"},
  126. tok=tok,
  127. )
  128. self.helper.send_event(
  129. room_id=room_id,
  130. type=EventTypes.Message,
  131. content={
  132. "msgtype": "m.text",
  133. "body": "with wrong label",
  134. EventContentFields.LABELS: ["#work"],
  135. },
  136. tok=tok,
  137. )
  138. self.helper.send_event(
  139. room_id=room_id,
  140. type=EventTypes.Message,
  141. content={
  142. "msgtype": "m.text",
  143. "body": "with two wrong labels",
  144. EventContentFields.LABELS: ["#work", "#notfun"],
  145. },
  146. tok=tok,
  147. )
  148. self.helper.send_event(
  149. room_id=room_id,
  150. type=EventTypes.Message,
  151. content={
  152. "msgtype": "m.text",
  153. "body": "with right label",
  154. EventContentFields.LABELS: ["#fun"],
  155. },
  156. tok=tok,
  157. )
  158. channel = self.make_request(
  159. "GET", "/sync?filter=%s" % sync_filter, access_token=tok
  160. )
  161. self.assertEqual(channel.code, 200, channel.result)
  162. return channel.json_body["rooms"]["join"][room_id]["timeline"]["events"]
  163. class SyncTypingTests(unittest.HomeserverTestCase):
  164. servlets = [
  165. synapse.rest.admin.register_servlets_for_client_rest_resource,
  166. room.register_servlets,
  167. login.register_servlets,
  168. sync.register_servlets,
  169. ]
  170. user_id = True
  171. hijack_auth = False
  172. def test_sync_backwards_typing(self) -> None:
  173. """
  174. If the typing serial goes backwards and the typing handler is then reset
  175. (such as when the master restarts and sets the typing serial to 0), we
  176. do not incorrectly return typing information that had a serial greater
  177. than the now-reset serial.
  178. """
  179. typing_url = "/rooms/%s/typing/%s?access_token=%s"
  180. sync_url = "/sync?timeout=3000000&access_token=%s&since=%s"
  181. # Register the user who gets notified
  182. user_id = self.register_user("user", "pass")
  183. access_token = self.login("user", "pass")
  184. # Register the user who sends the message
  185. other_user_id = self.register_user("otheruser", "pass")
  186. other_access_token = self.login("otheruser", "pass")
  187. # Create a room
  188. room = self.helper.create_room_as(user_id, tok=access_token)
  189. # Invite the other person
  190. self.helper.invite(room=room, src=user_id, tok=access_token, targ=other_user_id)
  191. # The other user joins
  192. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  193. # The other user sends some messages
  194. self.helper.send(room, body="Hi!", tok=other_access_token)
  195. self.helper.send(room, body="There!", tok=other_access_token)
  196. # Start typing.
  197. channel = self.make_request(
  198. "PUT",
  199. typing_url % (room, other_user_id, other_access_token),
  200. b'{"typing": true, "timeout": 30000}',
  201. )
  202. self.assertEqual(200, channel.code)
  203. channel = self.make_request("GET", "/sync?access_token=%s" % (access_token,))
  204. self.assertEqual(200, channel.code)
  205. next_batch = channel.json_body["next_batch"]
  206. # Stop typing.
  207. channel = self.make_request(
  208. "PUT",
  209. typing_url % (room, other_user_id, other_access_token),
  210. b'{"typing": false}',
  211. )
  212. self.assertEqual(200, channel.code)
  213. # Start typing.
  214. channel = self.make_request(
  215. "PUT",
  216. typing_url % (room, other_user_id, other_access_token),
  217. b'{"typing": true, "timeout": 30000}',
  218. )
  219. self.assertEqual(200, channel.code)
  220. # Should return immediately
  221. channel = self.make_request("GET", sync_url % (access_token, next_batch))
  222. self.assertEqual(200, channel.code)
  223. next_batch = channel.json_body["next_batch"]
  224. # Reset typing serial back to 0, as if the master had.
  225. typing = self.hs.get_typing_handler()
  226. typing._latest_room_serial = 0
  227. # Since it checks the state token, we need some state to update to
  228. # invalidate the stream token.
  229. self.helper.send(room, body="There!", tok=other_access_token)
  230. channel = self.make_request("GET", sync_url % (access_token, next_batch))
  231. self.assertEqual(200, channel.code)
  232. next_batch = channel.json_body["next_batch"]
  233. # This should time out! But it does not, because our stream token is
  234. # ahead, and therefore it's saying the typing (that we've actually
  235. # already seen) is new, since it's got a token above our new, now-reset
  236. # stream token.
  237. channel = self.make_request("GET", sync_url % (access_token, next_batch))
  238. self.assertEqual(200, channel.code)
  239. next_batch = channel.json_body["next_batch"]
  240. # Clear the typing information, so that it doesn't think everything is
  241. # in the future.
  242. typing._reset()
  243. # Now it SHOULD fail as it never completes!
  244. with self.assertRaises(TimedOutException):
  245. self.make_request("GET", sync_url % (access_token, next_batch))
  246. class SyncKnockTestCase(
  247. unittest.HomeserverTestCase, KnockingStrippedStateEventHelperMixin
  248. ):
  249. servlets = [
  250. synapse.rest.admin.register_servlets,
  251. login.register_servlets,
  252. room.register_servlets,
  253. sync.register_servlets,
  254. knock.register_servlets,
  255. ]
  256. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  257. self.store = hs.get_datastores().main
  258. self.url = "/sync?since=%s"
  259. self.next_batch = "s0"
  260. # Register the first user (used to create the room to knock on).
  261. self.user_id = self.register_user("kermit", "monkey")
  262. self.tok = self.login("kermit", "monkey")
  263. # Create the room we'll knock on.
  264. self.room_id = self.helper.create_room_as(
  265. self.user_id,
  266. is_public=False,
  267. room_version="7",
  268. tok=self.tok,
  269. )
  270. # Register the second user (used to knock on the room).
  271. self.knocker = self.register_user("knocker", "monkey")
  272. self.knocker_tok = self.login("knocker", "monkey")
  273. # Perform an initial sync for the knocking user.
  274. channel = self.make_request(
  275. "GET",
  276. self.url % self.next_batch,
  277. access_token=self.tok,
  278. )
  279. self.assertEqual(channel.code, 200, channel.json_body)
  280. # Store the next batch for the next request.
  281. self.next_batch = channel.json_body["next_batch"]
  282. # Set up some room state to test with.
  283. self.expected_room_state = self.send_example_state_events_to_room(
  284. hs, self.room_id, self.user_id
  285. )
  286. def test_knock_room_state(self) -> None:
  287. """Tests that /sync returns state from a room after knocking on it."""
  288. # Knock on a room
  289. channel = self.make_request(
  290. "POST",
  291. f"/_matrix/client/r0/knock/{self.room_id}",
  292. b"{}",
  293. self.knocker_tok,
  294. )
  295. self.assertEqual(200, channel.code, channel.result)
  296. # We expect to see the knock event in the stripped room state later
  297. self.expected_room_state[EventTypes.Member] = {
  298. "content": {"membership": "knock", "displayname": "knocker"},
  299. "state_key": "@knocker:test",
  300. }
  301. # Check that /sync includes stripped state from the room
  302. channel = self.make_request(
  303. "GET",
  304. self.url % self.next_batch,
  305. access_token=self.knocker_tok,
  306. )
  307. self.assertEqual(channel.code, 200, channel.json_body)
  308. # Extract the stripped room state events from /sync
  309. knock_entry = channel.json_body["rooms"]["knock"]
  310. room_state_events = knock_entry[self.room_id]["knock_state"]["events"]
  311. # Validate that the knock membership event came last
  312. self.assertEqual(room_state_events[-1]["type"], EventTypes.Member)
  313. # Validate the stripped room state events
  314. self.check_knock_room_state_against_room_state(
  315. room_state_events, self.expected_room_state
  316. )
  317. class ReadReceiptsTestCase(unittest.HomeserverTestCase):
  318. servlets = [
  319. synapse.rest.admin.register_servlets,
  320. login.register_servlets,
  321. receipts.register_servlets,
  322. room.register_servlets,
  323. sync.register_servlets,
  324. ]
  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. @override_config({"experimental_features": {"msc2285_enabled": True}})
  339. def test_private_read_receipts(self) -> None:
  340. # Send a message as the first user
  341. res = self.helper.send(self.room_id, body="hello", tok=self.tok)
  342. # Send a private read receipt to tell the server the first user's message was read
  343. channel = self.make_request(
  344. "POST",
  345. f"/rooms/{self.room_id}/receipt/org.matrix.msc2285.read.private/{res['event_id']}",
  346. {},
  347. access_token=self.tok2,
  348. )
  349. self.assertEqual(channel.code, 200)
  350. # Test that the first user can't see the other user's private read receipt
  351. self.assertIsNone(self._get_read_receipt())
  352. @override_config({"experimental_features": {"msc2285_enabled": True}})
  353. def test_public_receipt_can_override_private(self) -> None:
  354. """
  355. Sending a public read receipt to the same event which has a private read
  356. receipt should cause that receipt to become public.
  357. """
  358. # Send a message as the first user
  359. res = self.helper.send(self.room_id, body="hello", tok=self.tok)
  360. # Send a private read receipt
  361. channel = self.make_request(
  362. "POST",
  363. f"/rooms/{self.room_id}/receipt/{ReceiptTypes.READ_PRIVATE}/{res['event_id']}",
  364. {},
  365. access_token=self.tok2,
  366. )
  367. self.assertEqual(channel.code, 200)
  368. self.assertIsNone(self._get_read_receipt())
  369. # Send a public read receipt
  370. channel = self.make_request(
  371. "POST",
  372. f"/rooms/{self.room_id}/receipt/{ReceiptTypes.READ}/{res['event_id']}",
  373. {},
  374. access_token=self.tok2,
  375. )
  376. self.assertEqual(channel.code, 200)
  377. # Test that we did override the private read receipt
  378. self.assertNotEqual(self._get_read_receipt(), None)
  379. @override_config({"experimental_features": {"msc2285_enabled": True}})
  380. def test_private_receipt_cannot_override_public(self) -> None:
  381. """
  382. Sending a private read receipt to the same event which has a public read
  383. receipt should cause no change.
  384. """
  385. # Send a message as the first user
  386. res = self.helper.send(self.room_id, body="hello", tok=self.tok)
  387. # Send a public read receipt
  388. channel = self.make_request(
  389. "POST",
  390. f"/rooms/{self.room_id}/receipt/{ReceiptTypes.READ}/{res['event_id']}",
  391. {},
  392. access_token=self.tok2,
  393. )
  394. self.assertEqual(channel.code, 200)
  395. self.assertNotEqual(self._get_read_receipt(), None)
  396. # Send a private read receipt
  397. channel = self.make_request(
  398. "POST",
  399. f"/rooms/{self.room_id}/receipt/{ReceiptTypes.READ_PRIVATE}/{res['event_id']}",
  400. {},
  401. access_token=self.tok2,
  402. )
  403. self.assertEqual(channel.code, 200)
  404. # Test that we didn't override the public read receipt
  405. self.assertIsNone(self._get_read_receipt())
  406. def test_read_receipt_with_empty_body_is_rejected(self) -> None:
  407. # Send a message as the first user
  408. res = self.helper.send(self.room_id, body="hello", tok=self.tok)
  409. # Send a read receipt for this message with an empty body
  410. channel = self.make_request(
  411. "POST",
  412. f"/rooms/{self.room_id}/receipt/m.read/{res['event_id']}",
  413. access_token=self.tok2,
  414. )
  415. self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST)
  416. self.assertEqual(channel.json_body["errcode"], "M_NOT_JSON", channel.json_body)
  417. def _get_read_receipt(self) -> Optional[JsonDict]:
  418. """Syncs and returns the read receipt."""
  419. # Checks if event is a read receipt
  420. def is_read_receipt(event: JsonDict) -> bool:
  421. return event["type"] == EduTypes.RECEIPT
  422. # Sync
  423. channel = self.make_request(
  424. "GET",
  425. self.url % self.next_batch,
  426. access_token=self.tok,
  427. )
  428. self.assertEqual(channel.code, 200)
  429. # Store the next batch for the next request.
  430. self.next_batch = channel.json_body["next_batch"]
  431. if channel.json_body.get("rooms", None) is None:
  432. return None
  433. # Return the read receipt
  434. ephemeral_events = channel.json_body["rooms"]["join"][self.room_id][
  435. "ephemeral"
  436. ]["events"]
  437. receipt_event = filter(is_read_receipt, ephemeral_events)
  438. return next(receipt_event, None)
  439. class UnreadMessagesTestCase(unittest.HomeserverTestCase):
  440. servlets = [
  441. synapse.rest.admin.register_servlets,
  442. login.register_servlets,
  443. read_marker.register_servlets,
  444. room.register_servlets,
  445. sync.register_servlets,
  446. receipts.register_servlets,
  447. ]
  448. def default_config(self) -> JsonDict:
  449. config = super().default_config()
  450. config["experimental_features"] = {
  451. "msc2654_enabled": True,
  452. "msc2285_enabled": True,
  453. }
  454. return config
  455. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  456. self.url = "/sync?since=%s"
  457. self.next_batch = "s0"
  458. # Register the first user (used to check the unread counts).
  459. self.user_id = self.register_user("kermit", "monkey")
  460. self.tok = self.login("kermit", "monkey")
  461. # Create the room we'll check unread counts for.
  462. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  463. # Register the second user (used to send events to the room).
  464. self.user2 = self.register_user("kermit2", "monkey")
  465. self.tok2 = self.login("kermit2", "monkey")
  466. # Change the power levels of the room so that the second user can send state
  467. # events.
  468. self.helper.send_state(
  469. self.room_id,
  470. EventTypes.PowerLevels,
  471. {
  472. "users": {self.user_id: 100, self.user2: 100},
  473. "users_default": 0,
  474. "events": {
  475. "m.room.name": 50,
  476. "m.room.power_levels": 100,
  477. "m.room.history_visibility": 100,
  478. "m.room.canonical_alias": 50,
  479. "m.room.avatar": 50,
  480. "m.room.tombstone": 100,
  481. "m.room.server_acl": 100,
  482. "m.room.encryption": 100,
  483. },
  484. "events_default": 0,
  485. "state_default": 50,
  486. "ban": 50,
  487. "kick": 50,
  488. "redact": 50,
  489. "invite": 0,
  490. },
  491. tok=self.tok,
  492. )
  493. def test_unread_counts(self) -> None:
  494. """Tests that /sync returns the right value for the unread count (MSC2654)."""
  495. # Check that our own messages don't increase the unread count.
  496. self.helper.send(self.room_id, "hello", tok=self.tok)
  497. self._check_unread_count(0)
  498. # Join the new user and check that this doesn't increase the unread count.
  499. self.helper.join(room=self.room_id, user=self.user2, tok=self.tok2)
  500. self._check_unread_count(0)
  501. # Check that the new user sending a message increases our unread count.
  502. res = self.helper.send(self.room_id, "hello", tok=self.tok2)
  503. self._check_unread_count(1)
  504. # Send a read receipt to tell the server we've read the latest event.
  505. body = json.dumps({ReceiptTypes.READ: res["event_id"]}).encode("utf8")
  506. channel = self.make_request(
  507. "POST",
  508. f"/rooms/{self.room_id}/read_markers",
  509. body,
  510. access_token=self.tok,
  511. )
  512. self.assertEqual(channel.code, 200, channel.json_body)
  513. # Check that the unread counter is back to 0.
  514. self._check_unread_count(0)
  515. # Check that private read receipts don't break unread counts
  516. res = self.helper.send(self.room_id, "hello", tok=self.tok2)
  517. self._check_unread_count(1)
  518. # Send a read receipt to tell the server we've read the latest event.
  519. channel = self.make_request(
  520. "POST",
  521. f"/rooms/{self.room_id}/receipt/org.matrix.msc2285.read.private/{res['event_id']}",
  522. {},
  523. access_token=self.tok,
  524. )
  525. self.assertEqual(channel.code, 200, channel.json_body)
  526. # Check that the unread counter is back to 0.
  527. self._check_unread_count(0)
  528. # Check that room name changes increase the unread counter.
  529. self.helper.send_state(
  530. self.room_id,
  531. "m.room.name",
  532. {"name": "my super room"},
  533. tok=self.tok2,
  534. )
  535. self._check_unread_count(1)
  536. # Check that room topic changes increase the unread counter.
  537. self.helper.send_state(
  538. self.room_id,
  539. "m.room.topic",
  540. {"topic": "welcome!!!"},
  541. tok=self.tok2,
  542. )
  543. self._check_unread_count(2)
  544. # Check that encrypted messages increase the unread counter.
  545. self.helper.send_event(self.room_id, EventTypes.Encrypted, {}, tok=self.tok2)
  546. self._check_unread_count(3)
  547. # Check that custom events with a body increase the unread counter.
  548. result = self.helper.send_event(
  549. self.room_id,
  550. "org.matrix.custom_type",
  551. {"body": "hello"},
  552. tok=self.tok2,
  553. )
  554. event_id = result["event_id"]
  555. self._check_unread_count(4)
  556. # Check that edits don't increase the unread counter.
  557. self.helper.send_event(
  558. room_id=self.room_id,
  559. type=EventTypes.Message,
  560. content={
  561. "body": "hello",
  562. "msgtype": "m.text",
  563. "m.relates_to": {
  564. "rel_type": RelationTypes.REPLACE,
  565. "event_id": event_id,
  566. },
  567. },
  568. tok=self.tok2,
  569. )
  570. self._check_unread_count(4)
  571. # Check that notices don't increase the unread counter.
  572. self.helper.send_event(
  573. room_id=self.room_id,
  574. type=EventTypes.Message,
  575. content={"body": "hello", "msgtype": "m.notice"},
  576. tok=self.tok2,
  577. )
  578. self._check_unread_count(4)
  579. # Check that tombstone events changes increase the unread counter.
  580. res1 = self.helper.send_state(
  581. self.room_id,
  582. EventTypes.Tombstone,
  583. {"replacement_room": "!someroom:test"},
  584. tok=self.tok2,
  585. )
  586. self._check_unread_count(5)
  587. res2 = self.helper.send(self.room_id, "hello", tok=self.tok2)
  588. # Make sure both m.read and org.matrix.msc2285.read.private advance
  589. channel = self.make_request(
  590. "POST",
  591. f"/rooms/{self.room_id}/receipt/m.read/{res1['event_id']}",
  592. {},
  593. access_token=self.tok,
  594. )
  595. self.assertEqual(channel.code, 200, channel.json_body)
  596. self._check_unread_count(1)
  597. channel = self.make_request(
  598. "POST",
  599. f"/rooms/{self.room_id}/receipt/org.matrix.msc2285.read.private/{res2['event_id']}",
  600. {},
  601. access_token=self.tok,
  602. )
  603. self.assertEqual(channel.code, 200, channel.json_body)
  604. self._check_unread_count(0)
  605. # We test for both receipt types that influence notification counts
  606. @parameterized.expand([ReceiptTypes.READ, ReceiptTypes.READ_PRIVATE])
  607. def test_read_receipts_only_go_down(self, receipt_type: ReceiptTypes) -> 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/{receipt_type}/{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 org.matrix.msc2285.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/org.matrix.msc2285.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.append(self.excluded_room_id)
  762. def test_join_leave(self) -> None:
  763. """Tests that rooms are correctly excluded from the 'join' and 'leave' sections of
  764. sync responses.
  765. """
  766. channel = self.make_request("GET", "/sync", access_token=self.tok)
  767. self.assertEqual(channel.code, 200, channel.result)
  768. self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["join"])
  769. self.assertIn(self.included_room_id, channel.json_body["rooms"]["join"])
  770. self.helper.leave(self.excluded_room_id, self.user_id, tok=self.tok)
  771. self.helper.leave(self.included_room_id, self.user_id, tok=self.tok)
  772. channel = self.make_request(
  773. "GET",
  774. "/sync?since=" + channel.json_body["next_batch"],
  775. access_token=self.tok,
  776. )
  777. self.assertEqual(channel.code, 200, channel.result)
  778. self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["leave"])
  779. self.assertIn(self.included_room_id, channel.json_body["rooms"]["leave"])
  780. def test_invite(self) -> None:
  781. """Tests that rooms are correctly excluded from the 'invite' section of sync
  782. responses.
  783. """
  784. invitee = self.register_user("invitee", "password")
  785. invitee_tok = self.login("invitee", "password")
  786. self.helper.invite(self.excluded_room_id, self.user_id, invitee, tok=self.tok)
  787. self.helper.invite(self.included_room_id, self.user_id, invitee, tok=self.tok)
  788. channel = self.make_request("GET", "/sync", access_token=invitee_tok)
  789. self.assertEqual(channel.code, 200, channel.result)
  790. self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["invite"])
  791. self.assertIn(self.included_room_id, channel.json_body["rooms"]["invite"])