1
0

test_appservice.py 49 KB

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