test_http.py 37 KB

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