test_http.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. # Copyright 2018 New Vector
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Any, Dict, List, Optional, Tuple
  15. from unittest.mock import Mock
  16. from twisted.internet.defer import Deferred
  17. from twisted.test.proto_helpers import MemoryReactor
  18. import synapse.rest.admin
  19. from synapse.logging.context import make_deferred_yieldable
  20. from synapse.push import PusherConfig, PusherConfigException
  21. from synapse.rest.client import login, push_rule, pusher, receipts, room
  22. from synapse.server import HomeServer
  23. from synapse.storage.databases.main.registration import TokenLookupResult
  24. from synapse.types import JsonDict
  25. from synapse.util import Clock
  26. from tests.unittest import HomeserverTestCase, override_config
  27. class HTTPPusherTests(HomeserverTestCase):
  28. servlets = [
  29. synapse.rest.admin.register_servlets_for_client_rest_resource,
  30. room.register_servlets,
  31. login.register_servlets,
  32. receipts.register_servlets,
  33. push_rule.register_servlets,
  34. pusher.register_servlets,
  35. ]
  36. user_id = True
  37. hijack_auth = False
  38. def default_config(self) -> Dict[str, Any]:
  39. config = super().default_config()
  40. config["start_pushers"] = True
  41. return config
  42. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  43. self.push_attempts: List[Tuple[Deferred, str, dict]] = []
  44. m = Mock()
  45. def post_json_get_json(url, body):
  46. d: Deferred = Deferred()
  47. self.push_attempts.append((d, url, body))
  48. return make_deferred_yieldable(d)
  49. m.post_json_get_json = post_json_get_json
  50. hs = self.setup_test_homeserver(proxied_blacklisted_http_client=m)
  51. return hs
  52. def test_invalid_configuration(self) -> None:
  53. """Invalid push configurations should be rejected."""
  54. # Register the user who gets notified
  55. user_id = self.register_user("user", "pass")
  56. access_token = self.login("user", "pass")
  57. # Register the pusher
  58. user_tuple = self.get_success(
  59. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  60. )
  61. token_id = user_tuple.token_id
  62. def test_data(data: Optional[JsonDict]) -> None:
  63. self.get_failure(
  64. self.hs.get_pusherpool().add_or_update_pusher(
  65. user_id=user_id,
  66. access_token=token_id,
  67. kind="http",
  68. app_id="m.http",
  69. app_display_name="HTTP Push Notifications",
  70. device_display_name="pushy push",
  71. pushkey="a@example.com",
  72. lang=None,
  73. data=data,
  74. ),
  75. PusherConfigException,
  76. )
  77. # Data must be provided with a URL.
  78. test_data(None)
  79. test_data({})
  80. test_data({"url": 1})
  81. # A bare domain name isn't accepted.
  82. test_data({"url": "example.com"})
  83. # A URL without a path isn't accepted.
  84. test_data({"url": "http://example.com"})
  85. # A url with an incorrect path isn't accepted.
  86. test_data({"url": "http://example.com/foo"})
  87. def test_sends_http(self) -> None:
  88. """
  89. The HTTP pusher will send pushes for each message to a HTTP endpoint
  90. when configured to do so.
  91. """
  92. # Register the user who gets notified
  93. user_id = self.register_user("user", "pass")
  94. access_token = self.login("user", "pass")
  95. # Register the user who sends the message
  96. other_user_id = self.register_user("otheruser", "pass")
  97. other_access_token = self.login("otheruser", "pass")
  98. # Register the pusher
  99. user_tuple = self.get_success(
  100. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  101. )
  102. token_id = user_tuple.token_id
  103. self.get_success(
  104. self.hs.get_pusherpool().add_or_update_pusher(
  105. user_id=user_id,
  106. access_token=token_id,
  107. kind="http",
  108. app_id="m.http",
  109. app_display_name="HTTP Push Notifications",
  110. device_display_name="pushy push",
  111. pushkey="a@example.com",
  112. lang=None,
  113. data={"url": "http://example.com/_matrix/push/v1/notify"},
  114. )
  115. )
  116. # Create a room
  117. room = self.helper.create_room_as(user_id, tok=access_token)
  118. # The other user joins
  119. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  120. # The other user sends some messages
  121. self.helper.send(room, body="Hi!", tok=other_access_token)
  122. self.helper.send(room, body="There!", tok=other_access_token)
  123. # Get the stream ordering before it gets sent
  124. pushers = self.get_success(
  125. self.hs.get_datastores().main.get_pushers_by({"user_name": user_id})
  126. )
  127. pushers = list(pushers)
  128. self.assertEqual(len(pushers), 1)
  129. last_stream_ordering = pushers[0].last_stream_ordering
  130. # Advance time a bit, so the pusher will register something has happened
  131. self.pump()
  132. # It hasn't succeeded yet, so the stream ordering shouldn't have moved
  133. pushers = self.get_success(
  134. self.hs.get_datastores().main.get_pushers_by({"user_name": user_id})
  135. )
  136. pushers = list(pushers)
  137. self.assertEqual(len(pushers), 1)
  138. self.assertEqual(last_stream_ordering, pushers[0].last_stream_ordering)
  139. # One push was attempted to be sent -- it'll be the first message
  140. self.assertEqual(len(self.push_attempts), 1)
  141. self.assertEqual(
  142. self.push_attempts[0][1], "http://example.com/_matrix/push/v1/notify"
  143. )
  144. self.assertEqual(
  145. self.push_attempts[0][2]["notification"]["content"]["body"], "Hi!"
  146. )
  147. # Make the push succeed
  148. self.push_attempts[0][0].callback({})
  149. self.pump()
  150. # The stream ordering has increased
  151. pushers = self.get_success(
  152. self.hs.get_datastores().main.get_pushers_by({"user_name": user_id})
  153. )
  154. pushers = list(pushers)
  155. self.assertEqual(len(pushers), 1)
  156. self.assertTrue(pushers[0].last_stream_ordering > last_stream_ordering)
  157. last_stream_ordering = pushers[0].last_stream_ordering
  158. # Now it'll try and send the second push message, which will be the second one
  159. self.assertEqual(len(self.push_attempts), 2)
  160. self.assertEqual(
  161. self.push_attempts[1][1], "http://example.com/_matrix/push/v1/notify"
  162. )
  163. self.assertEqual(
  164. self.push_attempts[1][2]["notification"]["content"]["body"], "There!"
  165. )
  166. # Make the second push succeed
  167. self.push_attempts[1][0].callback({})
  168. self.pump()
  169. # The stream ordering has increased, again
  170. pushers = self.get_success(
  171. self.hs.get_datastores().main.get_pushers_by({"user_name": user_id})
  172. )
  173. pushers = list(pushers)
  174. self.assertEqual(len(pushers), 1)
  175. self.assertTrue(pushers[0].last_stream_ordering > last_stream_ordering)
  176. def test_sends_high_priority_for_encrypted(self) -> None:
  177. """
  178. The HTTP pusher will send pushes at high priority if they correspond
  179. to an encrypted message.
  180. This will happen both in 1:1 rooms and larger rooms.
  181. """
  182. # Register the user who gets notified
  183. user_id = self.register_user("user", "pass")
  184. access_token = self.login("user", "pass")
  185. # Register the user who sends the message
  186. other_user_id = self.register_user("otheruser", "pass")
  187. other_access_token = self.login("otheruser", "pass")
  188. # Register a third user
  189. yet_another_user_id = self.register_user("yetanotheruser", "pass")
  190. yet_another_access_token = self.login("yetanotheruser", "pass")
  191. # Create a room
  192. room = self.helper.create_room_as(user_id, tok=access_token)
  193. # The other user joins
  194. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  195. # Register the pusher
  196. user_tuple = self.get_success(
  197. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  198. )
  199. token_id = user_tuple.token_id
  200. self.get_success(
  201. self.hs.get_pusherpool().add_or_update_pusher(
  202. user_id=user_id,
  203. access_token=token_id,
  204. kind="http",
  205. app_id="m.http",
  206. app_display_name="HTTP Push Notifications",
  207. device_display_name="pushy push",
  208. pushkey="a@example.com",
  209. lang=None,
  210. data={"url": "http://example.com/_matrix/push/v1/notify"},
  211. )
  212. )
  213. # Send an encrypted event
  214. # I know there'd normally be set-up of an encrypted room first
  215. # but this will do for our purposes
  216. self.helper.send_event(
  217. room,
  218. "m.room.encrypted",
  219. content={
  220. "algorithm": "m.megolm.v1.aes-sha2",
  221. "sender_key": "6lImKbzK51MzWLwHh8tUM3UBBSBrLlgup/OOCGTvumM",
  222. "ciphertext": "AwgAErABoRxwpMipdgiwXgu46rHiWQ0DmRj0qUlPrMraBUDk"
  223. "leTnJRljpuc7IOhsYbLY3uo2WI0ab/ob41sV+3JEIhODJPqH"
  224. "TK7cEZaIL+/up9e+dT9VGF5kRTWinzjkeqO8FU5kfdRjm+3w"
  225. "0sy3o1OCpXXCfO+faPhbV/0HuK4ndx1G+myNfK1Nk/CxfMcT"
  226. "BT+zDS/Df/QePAHVbrr9uuGB7fW8ogW/ulnydgZPRluusFGv"
  227. "J3+cg9LoPpZPAmv5Me3ec7NtdlfN0oDZ0gk3TiNkkhsxDG9Y"
  228. "YcNzl78USI0q8+kOV26Bu5dOBpU4WOuojXZHJlP5lMgdzLLl"
  229. "EQ0",
  230. "session_id": "IigqfNWLL+ez/Is+Duwp2s4HuCZhFG9b9CZKTYHtQ4A",
  231. "device_id": "AHQDUSTAAA",
  232. },
  233. tok=other_access_token,
  234. )
  235. # Advance time a bit, so the pusher will register something has happened
  236. self.pump()
  237. # Make the push succeed
  238. self.push_attempts[0][0].callback({})
  239. self.pump()
  240. # Check our push made it with high priority
  241. self.assertEqual(len(self.push_attempts), 1)
  242. self.assertEqual(
  243. self.push_attempts[0][1], "http://example.com/_matrix/push/v1/notify"
  244. )
  245. self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high")
  246. # Add yet another person — we want to make this room not a 1:1
  247. # (as encrypted messages in a 1:1 currently have tweaks applied
  248. # so it doesn't properly exercise the condition of all encrypted
  249. # messages need to be high).
  250. self.helper.join(
  251. room=room, user=yet_another_user_id, tok=yet_another_access_token
  252. )
  253. # Check no push notifications are sent regarding the membership changes
  254. # (that would confuse the test)
  255. self.pump()
  256. self.assertEqual(len(self.push_attempts), 1)
  257. # Send another encrypted event
  258. self.helper.send_event(
  259. room,
  260. "m.room.encrypted",
  261. content={
  262. "ciphertext": "AwgAEoABtEuic/2DF6oIpNH+q/PonzlhXOVho8dTv0tzFr5m"
  263. "9vTo50yabx3nxsRlP2WxSqa8I07YftP+EKWCWJvTkg6o7zXq"
  264. "6CK+GVvLQOVgK50SfvjHqJXN+z1VEqj+5mkZVN/cAgJzoxcH"
  265. "zFHkwDPJC8kQs47IHd8EO9KBUK4v6+NQ1uE/BIak4qAf9aS/"
  266. "kI+f0gjn9IY9K6LXlah82A/iRyrIrxkCkE/n0VfvLhaWFecC"
  267. "sAWTcMLoF6fh1Jpke95mljbmFSpsSd/eEQw",
  268. "device_id": "SRCFTWTHXO",
  269. "session_id": "eMA+bhGczuTz1C5cJR1YbmrnnC6Goni4lbvS5vJ1nG4",
  270. "algorithm": "m.megolm.v1.aes-sha2",
  271. "sender_key": "rC/XSIAiYrVGSuaHMop8/pTZbku4sQKBZwRwukgnN1c",
  272. },
  273. tok=other_access_token,
  274. )
  275. # Advance time a bit, so the pusher will register something has happened
  276. self.pump()
  277. self.assertEqual(len(self.push_attempts), 2)
  278. self.assertEqual(
  279. self.push_attempts[1][1], "http://example.com/_matrix/push/v1/notify"
  280. )
  281. self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "high")
  282. def test_sends_high_priority_for_one_to_one_only(self) -> None:
  283. """
  284. The HTTP pusher will send pushes at high priority if they correspond
  285. to a message in a one-to-one room.
  286. """
  287. # Register the user who gets notified
  288. user_id = self.register_user("user", "pass")
  289. access_token = self.login("user", "pass")
  290. # Register the user who sends the message
  291. other_user_id = self.register_user("otheruser", "pass")
  292. other_access_token = self.login("otheruser", "pass")
  293. # Register a third user
  294. yet_another_user_id = self.register_user("yetanotheruser", "pass")
  295. yet_another_access_token = self.login("yetanotheruser", "pass")
  296. # Create a room
  297. room = self.helper.create_room_as(user_id, tok=access_token)
  298. # The other user joins
  299. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  300. # Register the pusher
  301. user_tuple = self.get_success(
  302. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  303. )
  304. token_id = user_tuple.token_id
  305. self.get_success(
  306. self.hs.get_pusherpool().add_or_update_pusher(
  307. user_id=user_id,
  308. access_token=token_id,
  309. kind="http",
  310. app_id="m.http",
  311. app_display_name="HTTP Push Notifications",
  312. device_display_name="pushy push",
  313. pushkey="a@example.com",
  314. lang=None,
  315. data={"url": "http://example.com/_matrix/push/v1/notify"},
  316. )
  317. )
  318. # Send a message
  319. self.helper.send(room, body="Hi!", tok=other_access_token)
  320. # Advance time a bit, so the pusher will register something has happened
  321. self.pump()
  322. # Make the push succeed
  323. self.push_attempts[0][0].callback({})
  324. self.pump()
  325. # Check our push made it with high priority — this is a one-to-one room
  326. self.assertEqual(len(self.push_attempts), 1)
  327. self.assertEqual(
  328. self.push_attempts[0][1], "http://example.com/_matrix/push/v1/notify"
  329. )
  330. self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high")
  331. # Yet another user joins
  332. self.helper.join(
  333. room=room, user=yet_another_user_id, tok=yet_another_access_token
  334. )
  335. # Check no push notifications are sent regarding the membership changes
  336. # (that would confuse the test)
  337. self.pump()
  338. self.assertEqual(len(self.push_attempts), 1)
  339. # Send another event
  340. self.helper.send(room, body="Welcome!", tok=other_access_token)
  341. # Advance time a bit, so the pusher will register something has happened
  342. self.pump()
  343. self.assertEqual(len(self.push_attempts), 2)
  344. self.assertEqual(
  345. self.push_attempts[1][1], "http://example.com/_matrix/push/v1/notify"
  346. )
  347. # check that this is low-priority
  348. self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low")
  349. def test_sends_high_priority_for_mention(self) -> None:
  350. """
  351. The HTTP pusher will send pushes at high priority if they correspond
  352. to a message containing the user's display name.
  353. """
  354. # Register the user who gets notified
  355. user_id = self.register_user("user", "pass")
  356. access_token = self.login("user", "pass")
  357. # Register the user who sends the message
  358. other_user_id = self.register_user("otheruser", "pass")
  359. other_access_token = self.login("otheruser", "pass")
  360. # Register a third user
  361. yet_another_user_id = self.register_user("yetanotheruser", "pass")
  362. yet_another_access_token = self.login("yetanotheruser", "pass")
  363. # Create a room
  364. room = self.helper.create_room_as(user_id, tok=access_token)
  365. # The other users join
  366. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  367. self.helper.join(
  368. room=room, user=yet_another_user_id, tok=yet_another_access_token
  369. )
  370. # Register the pusher
  371. user_tuple = self.get_success(
  372. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  373. )
  374. token_id = user_tuple.token_id
  375. self.get_success(
  376. self.hs.get_pusherpool().add_or_update_pusher(
  377. user_id=user_id,
  378. access_token=token_id,
  379. kind="http",
  380. app_id="m.http",
  381. app_display_name="HTTP Push Notifications",
  382. device_display_name="pushy push",
  383. pushkey="a@example.com",
  384. lang=None,
  385. data={"url": "http://example.com/_matrix/push/v1/notify"},
  386. )
  387. )
  388. # Send a message
  389. self.helper.send(room, body="Oh, user, hello!", tok=other_access_token)
  390. # Advance time a bit, so the pusher will register something has happened
  391. self.pump()
  392. # Make the push succeed
  393. self.push_attempts[0][0].callback({})
  394. self.pump()
  395. # Check our push made it with high priority
  396. self.assertEqual(len(self.push_attempts), 1)
  397. self.assertEqual(
  398. self.push_attempts[0][1], "http://example.com/_matrix/push/v1/notify"
  399. )
  400. self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high")
  401. # Send another event, this time with no mention
  402. self.helper.send(room, body="Are you there?", tok=other_access_token)
  403. # Advance time a bit, so the pusher will register something has happened
  404. self.pump()
  405. self.assertEqual(len(self.push_attempts), 2)
  406. self.assertEqual(
  407. self.push_attempts[1][1], "http://example.com/_matrix/push/v1/notify"
  408. )
  409. # check that this is low-priority
  410. self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low")
  411. def test_sends_high_priority_for_atroom(self) -> None:
  412. """
  413. The HTTP pusher will send pushes at high priority if they correspond
  414. to a message that contains @room.
  415. """
  416. # Register the user who gets notified
  417. user_id = self.register_user("user", "pass")
  418. access_token = self.login("user", "pass")
  419. # Register the user who sends the message
  420. other_user_id = self.register_user("otheruser", "pass")
  421. other_access_token = self.login("otheruser", "pass")
  422. # Register a third user
  423. yet_another_user_id = self.register_user("yetanotheruser", "pass")
  424. yet_another_access_token = self.login("yetanotheruser", "pass")
  425. # Create a room (as other_user so the power levels are compatible with
  426. # other_user sending @room).
  427. room = self.helper.create_room_as(other_user_id, tok=other_access_token)
  428. # The other users join
  429. self.helper.join(room=room, user=user_id, tok=access_token)
  430. self.helper.join(
  431. room=room, user=yet_another_user_id, tok=yet_another_access_token
  432. )
  433. # Register the pusher
  434. user_tuple = self.get_success(
  435. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  436. )
  437. token_id = user_tuple.token_id
  438. self.get_success(
  439. self.hs.get_pusherpool().add_or_update_pusher(
  440. user_id=user_id,
  441. access_token=token_id,
  442. kind="http",
  443. app_id="m.http",
  444. app_display_name="HTTP Push Notifications",
  445. device_display_name="pushy push",
  446. pushkey="a@example.com",
  447. lang=None,
  448. data={"url": "http://example.com/_matrix/push/v1/notify"},
  449. )
  450. )
  451. # Send a message
  452. self.helper.send(
  453. room,
  454. body="@room eeek! There's a spider on the table!",
  455. tok=other_access_token,
  456. )
  457. # Advance time a bit, so the pusher will register something has happened
  458. self.pump()
  459. # Make the push succeed
  460. self.push_attempts[0][0].callback({})
  461. self.pump()
  462. # Check our push made it with high priority
  463. self.assertEqual(len(self.push_attempts), 1)
  464. self.assertEqual(
  465. self.push_attempts[0][1], "http://example.com/_matrix/push/v1/notify"
  466. )
  467. self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high")
  468. # Send another event, this time as someone without the power of @room
  469. self.helper.send(
  470. room, body="@room the spider is gone", tok=yet_another_access_token
  471. )
  472. # Advance time a bit, so the pusher will register something has happened
  473. self.pump()
  474. self.assertEqual(len(self.push_attempts), 2)
  475. self.assertEqual(
  476. self.push_attempts[1][1], "http://example.com/_matrix/push/v1/notify"
  477. )
  478. # check that this is low-priority
  479. self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low")
  480. def test_push_unread_count_group_by_room(self) -> None:
  481. """
  482. The HTTP pusher will group unread count by number of unread rooms.
  483. """
  484. # Carry out common push count tests and setup
  485. self._test_push_unread_count()
  486. # Carry out our option-value specific test
  487. #
  488. # This push should still only contain an unread count of 1 (for 1 unread room)
  489. self._check_push_attempt(7, 1)
  490. @override_config({"push": {"group_unread_count_by_room": False}})
  491. def test_push_unread_count_message_count(self) -> None:
  492. """
  493. The HTTP pusher will send the total unread message count.
  494. """
  495. # Carry out common push count tests and setup
  496. self._test_push_unread_count()
  497. # Carry out our option-value specific test
  498. #
  499. # We're counting every unread message, so there should now be 3 since the
  500. # last read receipt
  501. self._check_push_attempt(7, 3)
  502. def _test_push_unread_count(self) -> None:
  503. """
  504. Tests that the correct unread count appears in sent push notifications
  505. Note that:
  506. * Sending messages will cause push notifications to go out to relevant users
  507. * Sending a read receipt will cause the HTTP pusher to check whether the unread
  508. count has changed since the last push notification. If so, a "badge update"
  509. notification goes out to the user that sent the receipt
  510. """
  511. # Register the user who gets notified
  512. user_id = self.register_user("user", "pass")
  513. access_token = self.login("user", "pass")
  514. # Register the user who sends the message
  515. other_user_id = self.register_user("other_user", "pass")
  516. other_access_token = self.login("other_user", "pass")
  517. # Create a room (as other_user)
  518. room_id = self.helper.create_room_as(other_user_id, tok=other_access_token)
  519. # The user to get notified joins
  520. self.helper.join(room=room_id, user=user_id, tok=access_token)
  521. # Register the pusher
  522. user_tuple = self.get_success(
  523. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  524. )
  525. token_id = user_tuple.token_id
  526. self.get_success(
  527. self.hs.get_pusherpool().add_or_update_pusher(
  528. user_id=user_id,
  529. access_token=token_id,
  530. kind="http",
  531. app_id="m.http",
  532. app_display_name="HTTP Push Notifications",
  533. device_display_name="pushy push",
  534. pushkey="a@example.com",
  535. lang=None,
  536. data={"url": "http://example.com/_matrix/push/v1/notify"},
  537. )
  538. )
  539. # Send a message
  540. response = self.helper.send(
  541. room_id, body="Hello there!", tok=other_access_token
  542. )
  543. first_message_event_id = response["event_id"]
  544. expected_push_attempts = 1
  545. self._check_push_attempt(expected_push_attempts, 1)
  546. self._send_read_request(access_token, first_message_event_id, room_id)
  547. # Unread count has changed. Therefore, ensure that read request triggers
  548. # a push notification.
  549. expected_push_attempts += 1
  550. self.assertEqual(len(self.push_attempts), expected_push_attempts)
  551. # Send another message
  552. response2 = self.helper.send(
  553. room_id, body="How's the weather today?", tok=other_access_token
  554. )
  555. second_message_event_id = response2["event_id"]
  556. expected_push_attempts += 1
  557. self._check_push_attempt(expected_push_attempts, 1)
  558. self._send_read_request(access_token, second_message_event_id, room_id)
  559. expected_push_attempts += 1
  560. self._check_push_attempt(expected_push_attempts, 0)
  561. # If we're grouping by room, sending more messages shouldn't increase the
  562. # unread count, as they're all being sent in the same room. Otherwise, it
  563. # should. Therefore, the last call to _check_push_attempt is done in the
  564. # caller method.
  565. self.helper.send(room_id, body="Hello?", tok=other_access_token)
  566. expected_push_attempts += 1
  567. self._advance_time_and_make_push_succeed(expected_push_attempts)
  568. self.helper.send(room_id, body="Hello??", tok=other_access_token)
  569. expected_push_attempts += 1
  570. self._advance_time_and_make_push_succeed(expected_push_attempts)
  571. self.helper.send(room_id, body="HELLO???", tok=other_access_token)
  572. def _advance_time_and_make_push_succeed(self, expected_push_attempts: int) -> None:
  573. self.pump()
  574. self.push_attempts[expected_push_attempts - 1][0].callback({})
  575. def _check_push_attempt(
  576. self, expected_push_attempts: int, expected_unread_count_last_push: int
  577. ) -> None:
  578. """
  579. Makes sure that the last expected push attempt succeeds and checks whether
  580. it contains the expected unread count.
  581. """
  582. self._advance_time_and_make_push_succeed(expected_push_attempts)
  583. # Check our push made it
  584. self.assertEqual(len(self.push_attempts), expected_push_attempts)
  585. _, push_url, push_body = self.push_attempts[expected_push_attempts - 1]
  586. self.assertEqual(
  587. push_url,
  588. "http://example.com/_matrix/push/v1/notify",
  589. )
  590. # Check that the unread count for the room is 0
  591. #
  592. # The unread count is zero as the user has no read receipt in the room yet
  593. self.assertEqual(
  594. push_body["notification"]["counts"]["unread"],
  595. expected_unread_count_last_push,
  596. )
  597. def _send_read_request(
  598. self, access_token: str, message_event_id: str, room_id: str
  599. ) -> None:
  600. # Now set the user's read receipt position to the first event
  601. #
  602. # This will actually trigger a new notification to be sent out so that
  603. # even if the user does not receive another message, their unread
  604. # count goes down
  605. channel = self.make_request(
  606. "POST",
  607. "/rooms/%s/receipt/m.read/%s" % (room_id, message_event_id),
  608. {},
  609. access_token=access_token,
  610. )
  611. self.assertEqual(channel.code, 200, channel.json_body)
  612. def _make_user_with_pusher(
  613. self, username: str, enabled: bool = True
  614. ) -> Tuple[str, str]:
  615. """Registers a user and creates a pusher for them.
  616. Args:
  617. username: the localpart of the new user's Matrix ID.
  618. enabled: whether to create the pusher in an enabled or disabled state.
  619. """
  620. user_id = self.register_user(username, "pass")
  621. access_token = self.login(username, "pass")
  622. # Register the pusher
  623. self._set_pusher(user_id, access_token, enabled)
  624. return user_id, access_token
  625. def _set_pusher(self, user_id: str, access_token: str, enabled: bool) -> None:
  626. """Creates or updates the pusher for the given user.
  627. Args:
  628. user_id: the user's Matrix ID.
  629. access_token: the access token associated with the pusher.
  630. enabled: whether to enable or disable the pusher.
  631. """
  632. user_tuple = self.get_success(
  633. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  634. )
  635. token_id = user_tuple.token_id
  636. self.get_success(
  637. self.hs.get_pusherpool().add_or_update_pusher(
  638. user_id=user_id,
  639. access_token=token_id,
  640. kind="http",
  641. app_id="m.http",
  642. app_display_name="HTTP Push Notifications",
  643. device_display_name="pushy push",
  644. pushkey="a@example.com",
  645. lang=None,
  646. data={"url": "http://example.com/_matrix/push/v1/notify"},
  647. enabled=enabled,
  648. device_id=user_tuple.device_id,
  649. )
  650. )
  651. def test_dont_notify_rule_overrides_message(self) -> None:
  652. """
  653. The override push rule will suppress notification
  654. """
  655. user_id, access_token = self._make_user_with_pusher("user")
  656. other_user_id, other_access_token = self._make_user_with_pusher("otheruser")
  657. # Create a room
  658. room = self.helper.create_room_as(user_id, tok=access_token)
  659. # Disable user notifications for this room -> user
  660. body = {
  661. "conditions": [{"kind": "event_match", "key": "room_id", "pattern": room}],
  662. "actions": ["dont_notify"],
  663. }
  664. channel = self.make_request(
  665. "PUT",
  666. "/pushrules/global/override/best.friend",
  667. body,
  668. access_token=access_token,
  669. )
  670. self.assertEqual(channel.code, 200)
  671. # Check we start with no pushes
  672. self.assertEqual(len(self.push_attempts), 0)
  673. # The other user joins
  674. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  675. # The other user sends a message (ignored by dont_notify push rule set above)
  676. self.helper.send(room, body="Hi!", tok=other_access_token)
  677. self.assertEqual(len(self.push_attempts), 0)
  678. # The user sends a message back (sends a notification)
  679. self.helper.send(room, body="Hello", tok=access_token)
  680. self.assertEqual(len(self.push_attempts), 1)
  681. @override_config({"experimental_features": {"msc3881_enabled": True}})
  682. def test_disable(self) -> None:
  683. """Tests that disabling a pusher means it's not pushed to anymore."""
  684. user_id, access_token = self._make_user_with_pusher("user")
  685. other_user_id, other_access_token = self._make_user_with_pusher("otheruser")
  686. room = self.helper.create_room_as(user_id, tok=access_token)
  687. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  688. # Send a message and check that it generated a push.
  689. self.helper.send(room, body="Hi!", tok=other_access_token)
  690. self.assertEqual(len(self.push_attempts), 1)
  691. # Disable the pusher.
  692. self._set_pusher(user_id, access_token, enabled=False)
  693. # Send another message and check that it did not generate a push.
  694. self.helper.send(room, body="Hi!", tok=other_access_token)
  695. self.assertEqual(len(self.push_attempts), 1)
  696. # Get the pushers for the user and check that it is marked as disabled.
  697. channel = self.make_request("GET", "/pushers", access_token=access_token)
  698. self.assertEqual(channel.code, 200)
  699. self.assertEqual(len(channel.json_body["pushers"]), 1)
  700. enabled = channel.json_body["pushers"][0]["org.matrix.msc3881.enabled"]
  701. self.assertFalse(enabled)
  702. self.assertTrue(isinstance(enabled, bool))
  703. @override_config({"experimental_features": {"msc3881_enabled": True}})
  704. def test_enable(self) -> None:
  705. """Tests that enabling a disabled pusher means it gets pushed to."""
  706. # Create the user with the pusher already disabled.
  707. user_id, access_token = self._make_user_with_pusher("user", enabled=False)
  708. other_user_id, other_access_token = self._make_user_with_pusher("otheruser")
  709. room = self.helper.create_room_as(user_id, tok=access_token)
  710. self.helper.join(room=room, user=other_user_id, tok=other_access_token)
  711. # Send a message and check that it did not generate a push.
  712. self.helper.send(room, body="Hi!", tok=other_access_token)
  713. self.assertEqual(len(self.push_attempts), 0)
  714. # Enable the pusher.
  715. self._set_pusher(user_id, access_token, enabled=True)
  716. # Send another message and check that it did generate a push.
  717. self.helper.send(room, body="Hi!", tok=other_access_token)
  718. self.assertEqual(len(self.push_attempts), 1)
  719. # Get the pushers for the user and check that it is marked as enabled.
  720. channel = self.make_request("GET", "/pushers", access_token=access_token)
  721. self.assertEqual(channel.code, 200)
  722. self.assertEqual(len(channel.json_body["pushers"]), 1)
  723. enabled = channel.json_body["pushers"][0]["org.matrix.msc3881.enabled"]
  724. self.assertTrue(enabled)
  725. self.assertTrue(isinstance(enabled, bool))
  726. @override_config({"experimental_features": {"msc3881_enabled": True}})
  727. def test_null_enabled(self) -> None:
  728. """Tests that a pusher that has an 'enabled' column set to NULL (eg pushers
  729. created before the column was introduced) is considered enabled.
  730. """
  731. # We intentionally set 'enabled' to None so that it's stored as NULL in the
  732. # database.
  733. user_id, access_token = self._make_user_with_pusher("user", enabled=None) # type: ignore[arg-type]
  734. channel = self.make_request("GET", "/pushers", access_token=access_token)
  735. self.assertEqual(channel.code, 200)
  736. self.assertEqual(len(channel.json_body["pushers"]), 1)
  737. self.assertTrue(channel.json_body["pushers"][0]["org.matrix.msc3881.enabled"])
  738. def test_update_different_device_access_token_device_id(self) -> None:
  739. """Tests that if we create a pusher from one device, the update it from another
  740. device, the access token and device ID associated with the pusher stays the
  741. same.
  742. """
  743. # Create a user with a pusher.
  744. user_id, access_token = self._make_user_with_pusher("user")
  745. # Get the token ID for the current access token, since that's what we store in
  746. # the pushers table. Also get the device ID from it.
  747. user_tuple = self.get_success(
  748. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  749. )
  750. token_id = user_tuple.token_id
  751. device_id = user_tuple.device_id
  752. # Generate a new access token, and update the pusher with it.
  753. new_token = self.login("user", "pass")
  754. self._set_pusher(user_id, new_token, enabled=False)
  755. # Get the current list of pushers for the user.
  756. ret = self.get_success(
  757. self.hs.get_datastores().main.get_pushers_by({"user_name": user_id})
  758. )
  759. pushers: List[PusherConfig] = list(ret)
  760. # Check that we still have one pusher, and that the access token and device ID
  761. # associated with it didn't change.
  762. self.assertEqual(len(pushers), 1)
  763. self.assertEqual(pushers[0].access_token, token_id)
  764. self.assertEqual(pushers[0].device_id, device_id)
  765. @override_config({"experimental_features": {"msc3881_enabled": True}})
  766. def test_device_id(self) -> None:
  767. """Tests that a pusher created with a given device ID shows that device ID in
  768. GET /pushers requests.
  769. """
  770. self.register_user("user", "pass")
  771. access_token = self.login("user", "pass")
  772. # We create the pusher with an HTTP request rather than with
  773. # _make_user_with_pusher so that we can test the device ID is correctly set when
  774. # creating a pusher via an API call.
  775. self.make_request(
  776. method="POST",
  777. path="/pushers/set",
  778. content={
  779. "kind": "http",
  780. "app_id": "m.http",
  781. "app_display_name": "HTTP Push Notifications",
  782. "device_display_name": "pushy push",
  783. "pushkey": "a@example.com",
  784. "lang": "en",
  785. "data": {"url": "http://example.com/_matrix/push/v1/notify"},
  786. },
  787. access_token=access_token,
  788. )
  789. # Look up the user info for the access token so we can compare the device ID.
  790. lookup_result: TokenLookupResult = self.get_success(
  791. self.hs.get_datastores().main.get_user_by_access_token(access_token)
  792. )
  793. # Get the user's devices and check it has the correct device ID.
  794. channel = self.make_request("GET", "/pushers", access_token=access_token)
  795. self.assertEqual(channel.code, 200)
  796. self.assertEqual(len(channel.json_body["pushers"]), 1)
  797. self.assertEqual(
  798. channel.json_body["pushers"][0]["org.matrix.msc3881.device_id"],
  799. lookup_result.device_id,
  800. )