test_sync.py 38 KB

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