test_appservice.py 44 KB

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