test_appservice.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. # Copyright 2015-2021 The Matrix.org Foundation C.I.C.
  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 Dict, Iterable, List, Optional
  15. from unittest.mock import Mock
  16. from parameterized import parameterized
  17. from twisted.internet import defer
  18. from twisted.test.proto_helpers import MemoryReactor
  19. import synapse.rest.admin
  20. import synapse.storage
  21. from synapse.appservice import (
  22. ApplicationService,
  23. TransactionOneTimeKeyCounts,
  24. TransactionUnusedFallbackKeys,
  25. )
  26. from synapse.handlers.appservice import ApplicationServicesHandler
  27. from synapse.rest.client import login, receipts, register, room, sendtodevice
  28. from synapse.server import HomeServer
  29. from synapse.types import RoomStreamToken
  30. from synapse.util import Clock
  31. from synapse.util.stringutils import random_string
  32. from tests import unittest
  33. from tests.test_utils import make_awaitable, simple_async_mock
  34. from tests.unittest import override_config
  35. from tests.utils import MockClock
  36. class AppServiceHandlerTestCase(unittest.TestCase):
  37. """Tests the ApplicationServicesHandler."""
  38. def setUp(self):
  39. self.mock_store = Mock()
  40. self.mock_as_api = Mock()
  41. self.mock_scheduler = Mock()
  42. hs = Mock()
  43. hs.get_datastores.return_value = Mock(main=self.mock_store)
  44. self.mock_store.get_received_ts.return_value = make_awaitable(0)
  45. self.mock_store.set_appservice_last_pos.return_value = make_awaitable(None)
  46. self.mock_store.set_appservice_stream_type_pos.return_value = make_awaitable(
  47. None
  48. )
  49. hs.get_application_service_api.return_value = self.mock_as_api
  50. hs.get_application_service_scheduler.return_value = self.mock_scheduler
  51. hs.get_clock.return_value = MockClock()
  52. self.handler = ApplicationServicesHandler(hs)
  53. self.event_source = hs.get_event_sources()
  54. def test_notify_interested_services(self):
  55. interested_service = self._mkservice(is_interested_in_event=True)
  56. services = [
  57. self._mkservice(is_interested_in_event=False),
  58. interested_service,
  59. self._mkservice(is_interested_in_event=False),
  60. ]
  61. self.mock_as_api.query_user.return_value = make_awaitable(True)
  62. self.mock_store.get_app_services.return_value = services
  63. self.mock_store.get_user_by_id.return_value = make_awaitable([])
  64. event = Mock(
  65. sender="@someone:anywhere", type="m.room.message", room_id="!foo:bar"
  66. )
  67. self.mock_store.get_new_events_for_appservice.side_effect = [
  68. make_awaitable((0, [])),
  69. make_awaitable((1, [event])),
  70. ]
  71. self.handler.notify_interested_services(RoomStreamToken(None, 1))
  72. self.mock_scheduler.enqueue_for_appservice.assert_called_once_with(
  73. interested_service, events=[event]
  74. )
  75. def test_query_user_exists_unknown_user(self):
  76. user_id = "@someone:anywhere"
  77. services = [self._mkservice(is_interested_in_event=True)]
  78. services[0].is_interested_in_user.return_value = True
  79. self.mock_store.get_app_services.return_value = services
  80. self.mock_store.get_user_by_id.return_value = make_awaitable(None)
  81. event = Mock(sender=user_id, type="m.room.message", room_id="!foo:bar")
  82. self.mock_as_api.query_user.return_value = make_awaitable(True)
  83. self.mock_store.get_new_events_for_appservice.side_effect = [
  84. make_awaitable((0, [event])),
  85. ]
  86. self.handler.notify_interested_services(RoomStreamToken(None, 0))
  87. self.mock_as_api.query_user.assert_called_once_with(services[0], user_id)
  88. def test_query_user_exists_known_user(self):
  89. user_id = "@someone:anywhere"
  90. services = [self._mkservice(is_interested_in_event=True)]
  91. services[0].is_interested_in_user.return_value = True
  92. self.mock_store.get_app_services.return_value = services
  93. self.mock_store.get_user_by_id.return_value = make_awaitable({"name": user_id})
  94. event = Mock(sender=user_id, type="m.room.message", room_id="!foo:bar")
  95. self.mock_as_api.query_user.return_value = make_awaitable(True)
  96. self.mock_store.get_new_events_for_appservice.side_effect = [
  97. make_awaitable((0, [event])),
  98. ]
  99. self.handler.notify_interested_services(RoomStreamToken(None, 0))
  100. self.assertFalse(
  101. self.mock_as_api.query_user.called,
  102. "query_user called when it shouldn't have been.",
  103. )
  104. def test_query_room_alias_exists(self):
  105. room_alias_str = "#foo:bar"
  106. room_alias = Mock()
  107. room_alias.to_string.return_value = room_alias_str
  108. room_id = "!alpha:bet"
  109. servers = ["aperture"]
  110. interested_service = self._mkservice_alias(is_room_alias_in_namespace=True)
  111. services = [
  112. self._mkservice_alias(is_room_alias_in_namespace=False),
  113. interested_service,
  114. self._mkservice_alias(is_room_alias_in_namespace=False),
  115. ]
  116. self.mock_as_api.query_alias.return_value = make_awaitable(True)
  117. self.mock_store.get_app_services.return_value = services
  118. self.mock_store.get_association_from_room_alias.return_value = make_awaitable(
  119. Mock(room_id=room_id, servers=servers)
  120. )
  121. result = self.successResultOf(
  122. defer.ensureDeferred(self.handler.query_room_alias_exists(room_alias))
  123. )
  124. self.mock_as_api.query_alias.assert_called_once_with(
  125. interested_service, room_alias_str
  126. )
  127. self.assertEqual(result.room_id, room_id)
  128. self.assertEqual(result.servers, servers)
  129. def test_get_3pe_protocols_no_appservices(self):
  130. self.mock_store.get_app_services.return_value = []
  131. response = self.successResultOf(
  132. defer.ensureDeferred(self.handler.get_3pe_protocols("my-protocol"))
  133. )
  134. self.mock_as_api.get_3pe_protocol.assert_not_called()
  135. self.assertEqual(response, {})
  136. def test_get_3pe_protocols_no_protocols(self):
  137. service = self._mkservice(False, [])
  138. self.mock_store.get_app_services.return_value = [service]
  139. response = self.successResultOf(
  140. defer.ensureDeferred(self.handler.get_3pe_protocols())
  141. )
  142. self.mock_as_api.get_3pe_protocol.assert_not_called()
  143. self.assertEqual(response, {})
  144. def test_get_3pe_protocols_protocol_no_response(self):
  145. service = self._mkservice(False, ["my-protocol"])
  146. self.mock_store.get_app_services.return_value = [service]
  147. self.mock_as_api.get_3pe_protocol.return_value = make_awaitable(None)
  148. response = self.successResultOf(
  149. defer.ensureDeferred(self.handler.get_3pe_protocols())
  150. )
  151. self.mock_as_api.get_3pe_protocol.assert_called_once_with(
  152. service, "my-protocol"
  153. )
  154. self.assertEqual(response, {})
  155. def test_get_3pe_protocols_select_one_protocol(self):
  156. service = self._mkservice(False, ["my-protocol"])
  157. self.mock_store.get_app_services.return_value = [service]
  158. self.mock_as_api.get_3pe_protocol.return_value = make_awaitable(
  159. {"x-protocol-data": 42, "instances": []}
  160. )
  161. response = self.successResultOf(
  162. defer.ensureDeferred(self.handler.get_3pe_protocols("my-protocol"))
  163. )
  164. self.mock_as_api.get_3pe_protocol.assert_called_once_with(
  165. service, "my-protocol"
  166. )
  167. self.assertEqual(
  168. response, {"my-protocol": {"x-protocol-data": 42, "instances": []}}
  169. )
  170. def test_get_3pe_protocols_one_protocol(self):
  171. service = self._mkservice(False, ["my-protocol"])
  172. self.mock_store.get_app_services.return_value = [service]
  173. self.mock_as_api.get_3pe_protocol.return_value = make_awaitable(
  174. {"x-protocol-data": 42, "instances": []}
  175. )
  176. response = self.successResultOf(
  177. defer.ensureDeferred(self.handler.get_3pe_protocols())
  178. )
  179. self.mock_as_api.get_3pe_protocol.assert_called_once_with(
  180. service, "my-protocol"
  181. )
  182. self.assertEqual(
  183. response, {"my-protocol": {"x-protocol-data": 42, "instances": []}}
  184. )
  185. def test_get_3pe_protocols_multiple_protocol(self):
  186. service_one = self._mkservice(False, ["my-protocol"])
  187. service_two = self._mkservice(False, ["other-protocol"])
  188. self.mock_store.get_app_services.return_value = [service_one, service_two]
  189. self.mock_as_api.get_3pe_protocol.return_value = make_awaitable(
  190. {"x-protocol-data": 42, "instances": []}
  191. )
  192. response = self.successResultOf(
  193. defer.ensureDeferred(self.handler.get_3pe_protocols())
  194. )
  195. self.mock_as_api.get_3pe_protocol.assert_called()
  196. self.assertEqual(
  197. response,
  198. {
  199. "my-protocol": {"x-protocol-data": 42, "instances": []},
  200. "other-protocol": {"x-protocol-data": 42, "instances": []},
  201. },
  202. )
  203. def test_get_3pe_protocols_multiple_info(self):
  204. service_one = self._mkservice(False, ["my-protocol"])
  205. service_two = self._mkservice(False, ["my-protocol"])
  206. async def get_3pe_protocol(service, unusedProtocol):
  207. if service == service_one:
  208. return {
  209. "x-protocol-data": 42,
  210. "instances": [{"desc": "Alice's service"}],
  211. }
  212. if service == service_two:
  213. return {
  214. "x-protocol-data": 36,
  215. "x-not-used": 45,
  216. "instances": [{"desc": "Bob's service"}],
  217. }
  218. raise Exception("Unexpected service")
  219. self.mock_store.get_app_services.return_value = [service_one, service_two]
  220. self.mock_as_api.get_3pe_protocol = get_3pe_protocol
  221. response = self.successResultOf(
  222. defer.ensureDeferred(self.handler.get_3pe_protocols())
  223. )
  224. # It's expected that the second service's data doesn't appear in the response
  225. self.assertEqual(
  226. response,
  227. {
  228. "my-protocol": {
  229. "x-protocol-data": 42,
  230. "instances": [
  231. {
  232. "desc": "Alice's service",
  233. },
  234. {"desc": "Bob's service"},
  235. ],
  236. },
  237. },
  238. )
  239. def test_notify_interested_services_ephemeral(self):
  240. """
  241. Test sending ephemeral events to the appservice handler are scheduled
  242. to be pushed out to interested appservices, and that the stream ID is
  243. updated accordingly.
  244. """
  245. interested_service = self._mkservice(is_interested_in_event=True)
  246. services = [interested_service]
  247. self.mock_store.get_app_services.return_value = services
  248. self.mock_store.get_type_stream_id_for_appservice.return_value = make_awaitable(
  249. 579
  250. )
  251. event = Mock(event_id="event_1")
  252. self.event_source.sources.receipt.get_new_events_as.return_value = (
  253. make_awaitable(([event], None))
  254. )
  255. self.handler.notify_interested_services_ephemeral(
  256. "receipt_key", 580, ["@fakerecipient:example.com"]
  257. )
  258. self.mock_scheduler.enqueue_for_appservice.assert_called_once_with(
  259. interested_service, ephemeral=[event]
  260. )
  261. self.mock_store.set_appservice_stream_type_pos.assert_called_once_with(
  262. interested_service,
  263. "read_receipt",
  264. 580,
  265. )
  266. def test_notify_interested_services_ephemeral_out_of_order(self):
  267. """
  268. Test sending out of order ephemeral events to the appservice handler
  269. are ignored.
  270. """
  271. interested_service = self._mkservice(is_interested_in_event=True)
  272. services = [interested_service]
  273. self.mock_store.get_app_services.return_value = services
  274. self.mock_store.get_type_stream_id_for_appservice.return_value = make_awaitable(
  275. 580
  276. )
  277. event = Mock(event_id="event_1")
  278. self.event_source.sources.receipt.get_new_events_as.return_value = (
  279. make_awaitable(([event], None))
  280. )
  281. self.handler.notify_interested_services_ephemeral(
  282. "receipt_key", 580, ["@fakerecipient:example.com"]
  283. )
  284. # This method will be called, but with an empty list of events
  285. self.mock_scheduler.enqueue_for_appservice.assert_called_once_with(
  286. interested_service, ephemeral=[]
  287. )
  288. def _mkservice(
  289. self, is_interested_in_event: bool, protocols: Optional[Iterable] = None
  290. ) -> Mock:
  291. """
  292. Create a new mock representing an ApplicationService.
  293. Args:
  294. is_interested_in_event: Whether this application service will be considered
  295. interested in all events.
  296. protocols: The third-party protocols that this application service claims to
  297. support.
  298. Returns:
  299. A mock representing the ApplicationService.
  300. """
  301. service = Mock()
  302. service.is_interested_in_event.return_value = make_awaitable(
  303. is_interested_in_event
  304. )
  305. service.token = "mock_service_token"
  306. service.url = "mock_service_url"
  307. service.protocols = protocols
  308. return service
  309. def _mkservice_alias(self, is_room_alias_in_namespace: bool) -> Mock:
  310. """
  311. Create a new mock representing an ApplicationService that is or is not interested
  312. any given room aliase.
  313. Args:
  314. is_room_alias_in_namespace: If true, the application service will be interested
  315. in all room aliases that are queried against it. If false, the application
  316. service will not be interested in any room aliases.
  317. Returns:
  318. A mock representing the ApplicationService.
  319. """
  320. service = Mock()
  321. service.is_room_alias_in_namespace.return_value = is_room_alias_in_namespace
  322. service.token = "mock_service_token"
  323. service.url = "mock_service_url"
  324. return service
  325. class ApplicationServicesHandlerSendEventsTestCase(unittest.HomeserverTestCase):
  326. """
  327. Tests that the ApplicationServicesHandler sends events to application
  328. services correctly.
  329. """
  330. servlets = [
  331. synapse.rest.admin.register_servlets_for_client_rest_resource,
  332. login.register_servlets,
  333. room.register_servlets,
  334. sendtodevice.register_servlets,
  335. receipts.register_servlets,
  336. ]
  337. def prepare(self, reactor, clock, hs):
  338. # Mock the ApplicationServiceScheduler's _TransactionController's send method so that
  339. # we can track any outgoing ephemeral events
  340. self.send_mock = simple_async_mock()
  341. hs.get_application_service_handler().scheduler.txn_ctrl.send = self.send_mock
  342. # Mock out application services, and allow defining our own in tests
  343. self._services: List[ApplicationService] = []
  344. self.hs.get_datastores().main.get_app_services = Mock(
  345. return_value=self._services
  346. )
  347. # A user on the homeserver.
  348. self.local_user_device_id = "local_device"
  349. self.local_user = self.register_user("local_user", "password")
  350. self.local_user_token = self.login(
  351. "local_user", "password", self.local_user_device_id
  352. )
  353. # A user on the homeserver which lies within an appservice's exclusive user namespace.
  354. self.exclusive_as_user_device_id = "exclusive_as_device"
  355. self.exclusive_as_user = self.register_user("exclusive_as_user", "password")
  356. self.exclusive_as_user_token = self.login(
  357. "exclusive_as_user", "password", self.exclusive_as_user_device_id
  358. )
  359. def test_sending_read_receipt_batches_to_application_services(self):
  360. """Tests that a large batch of read receipts are sent correctly to
  361. interested application services.
  362. """
  363. # Register an application service that's interested in a certain user
  364. # and room prefix
  365. interested_appservice = self._register_application_service(
  366. namespaces={
  367. ApplicationService.NS_USERS: [
  368. {
  369. "regex": "@exclusive_as_user:.+",
  370. "exclusive": True,
  371. }
  372. ],
  373. ApplicationService.NS_ROOMS: [
  374. {
  375. "regex": "!fakeroom_.*",
  376. "exclusive": True,
  377. }
  378. ],
  379. },
  380. )
  381. # "Complete" a transaction.
  382. # All this really does for us is make an entry in the application_services_state
  383. # database table, which tracks the current stream_token per stream ID per AS.
  384. self.get_success(
  385. self.hs.get_datastores().main.complete_appservice_txn(
  386. 0,
  387. interested_appservice,
  388. )
  389. )
  390. # Now, pretend that we receive a large burst of read receipts (300 total) that
  391. # all come in at once.
  392. for i in range(300):
  393. self.get_success(
  394. # Insert a fake read receipt into the database
  395. self.hs.get_datastores().main.insert_receipt(
  396. # We have to use unique room ID + user ID combinations here, as the db query
  397. # is an upsert.
  398. room_id=f"!fakeroom_{i}:test",
  399. receipt_type="m.read",
  400. user_id=self.local_user,
  401. event_ids=[f"$eventid_{i}"],
  402. data={},
  403. )
  404. )
  405. # Now notify the appservice handler that 300 read receipts have all arrived
  406. # at once. What will it do!
  407. # note: stream tokens start at 2
  408. for stream_token in range(2, 303):
  409. self.get_success(
  410. self.hs.get_application_service_handler()._notify_interested_services_ephemeral(
  411. services=[interested_appservice],
  412. stream_key="receipt_key",
  413. new_token=stream_token,
  414. users=[self.exclusive_as_user],
  415. )
  416. )
  417. # Using our txn send mock, we can see what the AS received. After iterating over every
  418. # transaction, we'd like to see all 300 read receipts accounted for.
  419. # No more, no less.
  420. all_ephemeral_events = []
  421. for call in self.send_mock.call_args_list:
  422. ephemeral_events = call[0][2]
  423. all_ephemeral_events += ephemeral_events
  424. # Ensure that no duplicate events were sent
  425. self.assertEqual(len(all_ephemeral_events), 300)
  426. # Check that the ephemeral event is a read receipt with the expected structure
  427. latest_read_receipt = all_ephemeral_events[-1]
  428. self.assertEqual(latest_read_receipt["type"], "m.receipt")
  429. event_id = list(latest_read_receipt["content"].keys())[0]
  430. self.assertEqual(
  431. latest_read_receipt["content"][event_id]["m.read"], {self.local_user: {}}
  432. )
  433. @unittest.override_config(
  434. {"experimental_features": {"msc2409_to_device_messages_enabled": True}}
  435. )
  436. def test_application_services_receive_local_to_device(self):
  437. """
  438. Test that when a user sends a to-device message to another user
  439. that is an application service's user namespace, the
  440. application service will receive it.
  441. """
  442. interested_appservice = self._register_application_service(
  443. namespaces={
  444. ApplicationService.NS_USERS: [
  445. {
  446. "regex": "@exclusive_as_user:.+",
  447. "exclusive": True,
  448. }
  449. ],
  450. },
  451. )
  452. # Have local_user send a to-device message to exclusive_as_user
  453. message_content = {"some_key": "some really interesting value"}
  454. chan = self.make_request(
  455. "PUT",
  456. "/_matrix/client/r0/sendToDevice/m.room_key_request/3",
  457. content={
  458. "messages": {
  459. self.exclusive_as_user: {
  460. self.exclusive_as_user_device_id: message_content
  461. }
  462. }
  463. },
  464. access_token=self.local_user_token,
  465. )
  466. self.assertEqual(chan.code, 200, chan.result)
  467. # Have exclusive_as_user send a to-device message to local_user
  468. chan = self.make_request(
  469. "PUT",
  470. "/_matrix/client/r0/sendToDevice/m.room_key_request/4",
  471. content={
  472. "messages": {
  473. self.local_user: {self.local_user_device_id: message_content}
  474. }
  475. },
  476. access_token=self.exclusive_as_user_token,
  477. )
  478. self.assertEqual(chan.code, 200, chan.result)
  479. # Check if our application service - that is interested in exclusive_as_user - received
  480. # the to-device message as part of an AS transaction.
  481. # Only the local_user -> exclusive_as_user to-device message should have been forwarded to the AS.
  482. #
  483. # The uninterested application service should not have been notified at all.
  484. self.send_mock.assert_called_once()
  485. (
  486. service,
  487. _events,
  488. _ephemeral,
  489. to_device_messages,
  490. _otks,
  491. _fbks,
  492. _device_list_summary,
  493. ) = self.send_mock.call_args[0]
  494. # Assert that this was the same to-device message that local_user sent
  495. self.assertEqual(service, interested_appservice)
  496. self.assertEqual(to_device_messages[0]["type"], "m.room_key_request")
  497. self.assertEqual(to_device_messages[0]["sender"], self.local_user)
  498. # Additional fields 'to_user_id' and 'to_device_id' specifically for
  499. # to-device messages via the AS API
  500. self.assertEqual(to_device_messages[0]["to_user_id"], self.exclusive_as_user)
  501. self.assertEqual(
  502. to_device_messages[0]["to_device_id"], self.exclusive_as_user_device_id
  503. )
  504. self.assertEqual(to_device_messages[0]["content"], message_content)
  505. @unittest.override_config(
  506. {"experimental_features": {"msc2409_to_device_messages_enabled": True}}
  507. )
  508. def test_application_services_receive_bursts_of_to_device(self):
  509. """
  510. Test that when a user sends >100 to-device messages at once, any
  511. interested AS's will receive them in separate transactions.
  512. Also tests that uninterested application services do not receive messages.
  513. """
  514. # Register two application services with exclusive interest in a user
  515. interested_appservices = []
  516. for _ in range(2):
  517. appservice = self._register_application_service(
  518. namespaces={
  519. ApplicationService.NS_USERS: [
  520. {
  521. "regex": "@exclusive_as_user:.+",
  522. "exclusive": True,
  523. }
  524. ],
  525. },
  526. )
  527. interested_appservices.append(appservice)
  528. # ...and an application service which does not have any user interest.
  529. self._register_application_service()
  530. to_device_message_content = {
  531. "some key": "some interesting value",
  532. }
  533. # We need to send a large burst of to-device messages. We also would like to
  534. # include them all in the same application service transaction so that we can
  535. # test large transactions.
  536. #
  537. # To do this, we can send a single to-device message to many user devices at
  538. # once.
  539. #
  540. # We insert number_of_messages - 1 messages into the database directly. We'll then
  541. # send a final to-device message to the real device, which will also kick off
  542. # an AS transaction (as just inserting messages into the DB won't).
  543. number_of_messages = 150
  544. fake_device_ids = [f"device_{num}" for num in range(number_of_messages - 1)]
  545. messages = {
  546. self.exclusive_as_user: {
  547. device_id: to_device_message_content for device_id in fake_device_ids
  548. }
  549. }
  550. # Create a fake device per message. We can't send to-device messages to
  551. # a device that doesn't exist.
  552. self.get_success(
  553. self.hs.get_datastores().main.db_pool.simple_insert_many(
  554. desc="test_application_services_receive_burst_of_to_device",
  555. table="devices",
  556. keys=("user_id", "device_id"),
  557. values=[
  558. (
  559. self.exclusive_as_user,
  560. device_id,
  561. )
  562. for device_id in fake_device_ids
  563. ],
  564. )
  565. )
  566. # Seed the device_inbox table with our fake messages
  567. self.get_success(
  568. self.hs.get_datastores().main.add_messages_to_device_inbox(messages, {})
  569. )
  570. # Now have local_user send a final to-device message to exclusive_as_user. All unsent
  571. # to-device messages should be sent to any application services
  572. # interested in exclusive_as_user.
  573. chan = self.make_request(
  574. "PUT",
  575. "/_matrix/client/r0/sendToDevice/m.room_key_request/4",
  576. content={
  577. "messages": {
  578. self.exclusive_as_user: {
  579. self.exclusive_as_user_device_id: to_device_message_content
  580. }
  581. }
  582. },
  583. access_token=self.local_user_token,
  584. )
  585. self.assertEqual(chan.code, 200, chan.result)
  586. self.send_mock.assert_called()
  587. # Count the total number of to-device messages that were sent out per-service.
  588. # Ensure that we only sent to-device messages to interested services, and that
  589. # each interested service received the full count of to-device messages.
  590. service_id_to_message_count: Dict[str, int] = {}
  591. for call in self.send_mock.call_args_list:
  592. (
  593. service,
  594. _events,
  595. _ephemeral,
  596. to_device_messages,
  597. _otks,
  598. _fbks,
  599. _device_list_summary,
  600. ) = call[0]
  601. # Check that this was made to an interested service
  602. self.assertIn(service, interested_appservices)
  603. # Add to the count of messages for this application service
  604. service_id_to_message_count.setdefault(service.id, 0)
  605. service_id_to_message_count[service.id] += len(to_device_messages)
  606. # Assert that each interested service received the full count of messages
  607. for count in service_id_to_message_count.values():
  608. self.assertEqual(count, number_of_messages)
  609. def _register_application_service(
  610. self,
  611. namespaces: Optional[Dict[str, Iterable[Dict]]] = None,
  612. ) -> ApplicationService:
  613. """
  614. Register a new application service, with the given namespaces of interest.
  615. Args:
  616. namespaces: A dictionary containing any user, room or alias namespaces that
  617. the application service is interested in.
  618. Returns:
  619. The registered application service.
  620. """
  621. # Create an application service
  622. appservice = ApplicationService(
  623. token=random_string(10),
  624. hostname="example.com",
  625. id=random_string(10),
  626. sender="@as:example.com",
  627. rate_limited=False,
  628. namespaces=namespaces,
  629. supports_ephemeral=True,
  630. )
  631. # Register the application service
  632. self._services.append(appservice)
  633. return appservice
  634. class ApplicationServicesHandlerDeviceListsTestCase(unittest.HomeserverTestCase):
  635. """
  636. Tests that the ApplicationServicesHandler sends device list updates to application
  637. services correctly.
  638. """
  639. servlets = [
  640. synapse.rest.admin.register_servlets_for_client_rest_resource,
  641. login.register_servlets,
  642. room.register_servlets,
  643. ]
  644. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  645. # Allow us to modify cached feature flags mid-test
  646. self.as_handler = hs.get_application_service_handler()
  647. # Mock ApplicationServiceApi's put_json, so we can verify the raw JSON that
  648. # will be sent over the wire
  649. self.put_json = simple_async_mock()
  650. hs.get_application_service_api().put_json = self.put_json # type: ignore[assignment]
  651. # Mock out application services, and allow defining our own in tests
  652. self._services: List[ApplicationService] = []
  653. self.hs.get_datastores().main.get_app_services = Mock(
  654. return_value=self._services
  655. )
  656. # Test across a variety of configuration values
  657. @parameterized.expand(
  658. [
  659. (True, True, True),
  660. (True, False, False),
  661. (False, True, False),
  662. (False, False, False),
  663. ]
  664. )
  665. def test_application_service_receives_device_list_updates(
  666. self,
  667. experimental_feature_enabled: bool,
  668. as_supports_txn_extensions: bool,
  669. as_should_receive_device_list_updates: bool,
  670. ):
  671. """
  672. Tests that an application service receives notice of changed device
  673. lists for a user, when a user changes their device lists.
  674. Arguments above are populated by parameterized.
  675. Args:
  676. as_should_receive_device_list_updates: Whether we expect the AS to receive the
  677. device list changes.
  678. experimental_feature_enabled: Whether the "msc3202_transaction_extensions" experimental
  679. feature is enabled. This feature must be enabled for device lists to ASs to work.
  680. as_supports_txn_extensions: Whether the application service has explicitly registered
  681. to receive information defined by MSC3202 - which includes device list changes.
  682. """
  683. # Change whether the experimental feature is enabled or disabled before making
  684. # device list changes
  685. self.as_handler._msc3202_transaction_extensions_enabled = (
  686. experimental_feature_enabled
  687. )
  688. # Create an appservice that is interested in "local_user"
  689. appservice = ApplicationService(
  690. token=random_string(10),
  691. hostname="example.com",
  692. id=random_string(10),
  693. sender="@as:example.com",
  694. rate_limited=False,
  695. namespaces={
  696. ApplicationService.NS_USERS: [
  697. {
  698. "regex": "@local_user:.+",
  699. "exclusive": False,
  700. }
  701. ],
  702. },
  703. supports_ephemeral=True,
  704. msc3202_transaction_extensions=as_supports_txn_extensions,
  705. # Must be set for Synapse to try pushing data to the AS
  706. hs_token="abcde",
  707. url="some_url",
  708. )
  709. # Register the application service
  710. self._services.append(appservice)
  711. # Register a user on the homeserver
  712. self.local_user = self.register_user("local_user", "password")
  713. self.local_user_token = self.login("local_user", "password")
  714. if as_should_receive_device_list_updates:
  715. # Ensure that the resulting JSON uses the unstable prefix and contains the
  716. # expected users
  717. self.put_json.assert_called_once()
  718. json_body = self.put_json.call_args[1]["json_body"]
  719. # Our application service should have received a device list update with
  720. # "local_user" in the "changed" list
  721. device_list_dict = json_body.get("org.matrix.msc3202.device_lists", {})
  722. self.assertEqual([], device_list_dict["left"])
  723. self.assertEqual([self.local_user], device_list_dict["changed"])
  724. else:
  725. # No device list changes should have been sent out
  726. self.put_json.assert_not_called()
  727. class ApplicationServicesHandlerOtkCountsTestCase(unittest.HomeserverTestCase):
  728. # Argument indices for pulling out arguments from a `send_mock`.
  729. ARG_OTK_COUNTS = 4
  730. ARG_FALLBACK_KEYS = 5
  731. servlets = [
  732. synapse.rest.admin.register_servlets_for_client_rest_resource,
  733. login.register_servlets,
  734. register.register_servlets,
  735. room.register_servlets,
  736. sendtodevice.register_servlets,
  737. receipts.register_servlets,
  738. ]
  739. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  740. # Mock the ApplicationServiceScheduler's _TransactionController's send method so that
  741. # we can track what's going out
  742. self.send_mock = simple_async_mock()
  743. hs.get_application_service_handler().scheduler.txn_ctrl.send = self.send_mock # type: ignore[assignment] # We assign to a method.
  744. # Define an application service for the tests
  745. self._service_token = "VERYSECRET"
  746. self._service = ApplicationService(
  747. self._service_token,
  748. "as1.invalid",
  749. "as1",
  750. "@as.sender:test",
  751. namespaces={
  752. "users": [
  753. {"regex": "@_as_.*:test", "exclusive": True},
  754. {"regex": "@as.sender:test", "exclusive": True},
  755. ]
  756. },
  757. msc3202_transaction_extensions=True,
  758. )
  759. self.hs.get_datastores().main.services_cache = [self._service]
  760. # Register some appservice users
  761. self._sender_user, self._sender_device = self.register_appservice_user(
  762. "as.sender", self._service_token
  763. )
  764. self._namespaced_user, self._namespaced_device = self.register_appservice_user(
  765. "_as_user1", self._service_token
  766. )
  767. # Register a real user as well.
  768. self._real_user = self.register_user("real.user", "meow")
  769. self._real_user_token = self.login("real.user", "meow")
  770. async def _add_otks_for_device(
  771. self, user_id: str, device_id: str, otk_count: int
  772. ) -> None:
  773. """
  774. Add some dummy keys. It doesn't matter if they're not a real algorithm;
  775. that should be opaque to the server anyway.
  776. """
  777. await self.hs.get_datastores().main.add_e2e_one_time_keys(
  778. user_id,
  779. device_id,
  780. self.clock.time_msec(),
  781. [("algo", f"k{i}", "{}") for i in range(otk_count)],
  782. )
  783. async def _add_fallback_key_for_device(
  784. self, user_id: str, device_id: str, used: bool
  785. ) -> None:
  786. """
  787. Adds a fake fallback key to a device, optionally marking it as used
  788. right away.
  789. """
  790. store = self.hs.get_datastores().main
  791. await store.set_e2e_fallback_keys(user_id, device_id, {"algo:fk": "fall back!"})
  792. if used is True:
  793. # Mark the key as used
  794. await store.db_pool.simple_update_one(
  795. table="e2e_fallback_keys_json",
  796. keyvalues={
  797. "user_id": user_id,
  798. "device_id": device_id,
  799. "algorithm": "algo",
  800. "key_id": "fk",
  801. },
  802. updatevalues={"used": True},
  803. desc="_get_fallback_key_set_used",
  804. )
  805. def _set_up_devices_and_a_room(self) -> str:
  806. """
  807. Helper to set up devices for all the users
  808. and a room for the users to talk in.
  809. """
  810. async def preparation():
  811. await self._add_otks_for_device(self._sender_user, self._sender_device, 42)
  812. await self._add_fallback_key_for_device(
  813. self._sender_user, self._sender_device, used=True
  814. )
  815. await self._add_otks_for_device(
  816. self._namespaced_user, self._namespaced_device, 36
  817. )
  818. await self._add_fallback_key_for_device(
  819. self._namespaced_user, self._namespaced_device, used=False
  820. )
  821. # Register a device for the real user, too, so that we can later ensure
  822. # that we don't leak information to the AS about the non-AS user.
  823. await self.hs.get_datastores().main.store_device(
  824. self._real_user, "REALDEV", "UltraMatrix 3000"
  825. )
  826. await self._add_otks_for_device(self._real_user, "REALDEV", 50)
  827. self.get_success(preparation())
  828. room_id = self.helper.create_room_as(
  829. self._real_user, is_public=True, tok=self._real_user_token
  830. )
  831. self.helper.join(
  832. room_id,
  833. self._namespaced_user,
  834. tok=self._service_token,
  835. appservice_user_id=self._namespaced_user,
  836. )
  837. # Check it was called for sanity. (This was to send the join event to the AS.)
  838. self.send_mock.assert_called()
  839. self.send_mock.reset_mock()
  840. return room_id
  841. @override_config(
  842. {"experimental_features": {"msc3202_transaction_extensions": True}}
  843. )
  844. def test_application_services_receive_otk_counts_and_fallback_key_usages_with_pdus(
  845. self,
  846. ) -> None:
  847. """
  848. Tests that:
  849. - the AS receives one-time key counts and unused fallback keys for:
  850. - the specified sender; and
  851. - any user who is in receipt of the PDUs
  852. """
  853. room_id = self._set_up_devices_and_a_room()
  854. # Send a message into the AS's room
  855. self.helper.send(room_id, "woof woof", tok=self._real_user_token)
  856. # Capture what was sent as an AS transaction.
  857. self.send_mock.assert_called()
  858. last_args, _last_kwargs = self.send_mock.call_args
  859. otks: Optional[TransactionOneTimeKeyCounts] = last_args[self.ARG_OTK_COUNTS]
  860. unused_fallbacks: Optional[TransactionUnusedFallbackKeys] = last_args[
  861. self.ARG_FALLBACK_KEYS
  862. ]
  863. self.assertEqual(
  864. otks,
  865. {
  866. "@as.sender:test": {self._sender_device: {"algo": 42}},
  867. "@_as_user1:test": {self._namespaced_device: {"algo": 36}},
  868. },
  869. )
  870. self.assertEqual(
  871. unused_fallbacks,
  872. {
  873. "@as.sender:test": {self._sender_device: []},
  874. "@_as_user1:test": {self._namespaced_device: ["algo"]},
  875. },
  876. )