test_appservice.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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
  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(None, 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(None, 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(None, 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. "receipt_key", 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. "receipt_key", 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[assignment]
  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[assignment]
  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. def _notify_interested_services(self) -> None:
  372. # This is normally set in `notify_interested_services` but we need to call the
  373. # internal async version so the reactor gets pushed to completion.
  374. self.hs.get_application_service_handler().current_max += 1
  375. self.get_success(
  376. self.hs.get_application_service_handler()._notify_interested_services(
  377. RoomStreamToken(
  378. None, self.hs.get_application_service_handler().current_max
  379. )
  380. )
  381. )
  382. @parameterized.expand(
  383. [
  384. ("@local_as_user:test", True),
  385. # Defining remote users in an application service user namespace regex is a
  386. # footgun since the appservice might assume that it'll receive all events
  387. # sent by that remote user, but it will only receive events in rooms that
  388. # are shared with a local user. So we just remove this footgun possibility
  389. # entirely and we won't notify the application service based on remote
  390. # users.
  391. ("@remote_as_user:remote", False),
  392. ]
  393. )
  394. def test_match_interesting_room_members(
  395. self, interesting_user: str, should_notify: bool
  396. ) -> None:
  397. """
  398. Test to make sure that a interesting user (local or remote) in the room is
  399. notified as expected when someone else in the room sends a message.
  400. """
  401. # Register an application service that's interested in the `interesting_user`
  402. interested_appservice = self._register_application_service(
  403. namespaces={
  404. ApplicationService.NS_USERS: [
  405. {
  406. "regex": interesting_user,
  407. "exclusive": False,
  408. },
  409. ],
  410. },
  411. )
  412. # Create a room
  413. alice = self.register_user("alice", "pass")
  414. alice_access_token = self.login("alice", "pass")
  415. room_id = self.helper.create_room_as(room_creator=alice, tok=alice_access_token)
  416. # Join the interesting user to the room
  417. self.get_success(
  418. event_injection.inject_member_event(
  419. self.hs, room_id, interesting_user, "join"
  420. )
  421. )
  422. # Kick the appservice into checking this membership event to get the event out
  423. # of the way
  424. self._notify_interested_services()
  425. # We don't care about the interesting user join event (this test is making sure
  426. # the next thing works)
  427. self.send_mock.reset_mock()
  428. # Send a message from an uninteresting user
  429. self.helper.send_event(
  430. room_id,
  431. type=EventTypes.Message,
  432. content={
  433. "msgtype": "m.text",
  434. "body": "message from uninteresting user",
  435. },
  436. tok=alice_access_token,
  437. )
  438. # Kick the appservice into checking this new event
  439. self._notify_interested_services()
  440. if should_notify:
  441. self.send_mock.assert_called_once()
  442. (
  443. service,
  444. events,
  445. _ephemeral,
  446. _to_device_messages,
  447. _otks,
  448. _fbks,
  449. _device_list_summary,
  450. ) = self.send_mock.call_args[0]
  451. # Even though the message came from an uninteresting user, it should still
  452. # notify us because the interesting user is joined to the room where the
  453. # message was sent.
  454. self.assertEqual(service, interested_appservice)
  455. self.assertEqual(events[0]["type"], "m.room.message")
  456. self.assertEqual(events[0]["sender"], alice)
  457. else:
  458. self.send_mock.assert_not_called()
  459. def test_application_services_receive_events_sent_by_interesting_local_user(
  460. self,
  461. ) -> None:
  462. """
  463. Test to make sure that a messages sent from a local user can be interesting and
  464. picked up by the appservice.
  465. """
  466. # Register an application service that's interested in all local users
  467. interested_appservice = self._register_application_service(
  468. namespaces={
  469. ApplicationService.NS_USERS: [
  470. {
  471. "regex": ".*",
  472. "exclusive": False,
  473. },
  474. ],
  475. },
  476. )
  477. # Create a room
  478. alice = self.register_user("alice", "pass")
  479. alice_access_token = self.login("alice", "pass")
  480. room_id = self.helper.create_room_as(room_creator=alice, tok=alice_access_token)
  481. # We don't care about interesting events before this (this test is making sure
  482. # the next thing works)
  483. self.send_mock.reset_mock()
  484. # Send a message from the interesting local user
  485. self.helper.send_event(
  486. room_id,
  487. type=EventTypes.Message,
  488. content={
  489. "msgtype": "m.text",
  490. "body": "message from interesting local user",
  491. },
  492. tok=alice_access_token,
  493. )
  494. # Kick the appservice into checking this new event
  495. self._notify_interested_services()
  496. self.send_mock.assert_called_once()
  497. (
  498. service,
  499. events,
  500. _ephemeral,
  501. _to_device_messages,
  502. _otks,
  503. _fbks,
  504. _device_list_summary,
  505. ) = self.send_mock.call_args[0]
  506. # Events sent from an interesting local user should also be picked up as
  507. # interesting to the appservice.
  508. self.assertEqual(service, interested_appservice)
  509. self.assertEqual(events[0]["type"], "m.room.message")
  510. self.assertEqual(events[0]["sender"], alice)
  511. def test_sending_read_receipt_batches_to_application_services(self) -> None:
  512. """Tests that a large batch of read receipts are sent correctly to
  513. interested application services.
  514. """
  515. # Register an application service that's interested in a certain user
  516. # and room prefix
  517. interested_appservice = self._register_application_service(
  518. namespaces={
  519. ApplicationService.NS_USERS: [
  520. {
  521. "regex": "@exclusive_as_user:.+",
  522. "exclusive": True,
  523. }
  524. ],
  525. ApplicationService.NS_ROOMS: [
  526. {
  527. "regex": "!fakeroom_.*",
  528. "exclusive": True,
  529. }
  530. ],
  531. },
  532. )
  533. # Now, pretend that we receive a large burst of read receipts (300 total) that
  534. # all come in at once.
  535. for i in range(300):
  536. self.get_success(
  537. # Insert a fake read receipt into the database
  538. self.hs.get_datastores().main.insert_receipt(
  539. # We have to use unique room ID + user ID combinations here, as the db query
  540. # is an upsert.
  541. room_id=f"!fakeroom_{i}:test",
  542. receipt_type="m.read",
  543. user_id=self.local_user,
  544. event_ids=[f"$eventid_{i}"],
  545. thread_id=None,
  546. data={},
  547. )
  548. )
  549. # Now notify the appservice handler that 300 read receipts have all arrived
  550. # at once. What will it do!
  551. # note: stream tokens start at 2
  552. for stream_token in range(2, 303):
  553. self.get_success(
  554. self.hs.get_application_service_handler()._notify_interested_services_ephemeral(
  555. services=[interested_appservice],
  556. stream_key="receipt_key",
  557. new_token=stream_token,
  558. users=[self.exclusive_as_user],
  559. )
  560. )
  561. # Using our txn send mock, we can see what the AS received. After iterating over every
  562. # transaction, we'd like to see all 300 read receipts accounted for.
  563. # No more, no less.
  564. all_ephemeral_events = []
  565. for call in self.send_mock.call_args_list:
  566. ephemeral_events = call[0][2]
  567. all_ephemeral_events += ephemeral_events
  568. # Ensure that no duplicate events were sent
  569. self.assertEqual(len(all_ephemeral_events), 300)
  570. # Check that the ephemeral event is a read receipt with the expected structure
  571. latest_read_receipt = all_ephemeral_events[-1]
  572. self.assertEqual(latest_read_receipt["type"], EduTypes.RECEIPT)
  573. event_id = list(latest_read_receipt["content"].keys())[0]
  574. self.assertEqual(
  575. latest_read_receipt["content"][event_id]["m.read"], {self.local_user: {}}
  576. )
  577. @unittest.override_config(
  578. {"experimental_features": {"msc2409_to_device_messages_enabled": True}}
  579. )
  580. def test_application_services_receive_local_to_device(self) -> None:
  581. """
  582. Test that when a user sends a to-device message to another user
  583. that is an application service's user namespace, the
  584. application service will receive it.
  585. """
  586. interested_appservice = self._register_application_service(
  587. namespaces={
  588. ApplicationService.NS_USERS: [
  589. {
  590. "regex": "@exclusive_as_user:.+",
  591. "exclusive": True,
  592. }
  593. ],
  594. },
  595. )
  596. # Have local_user send a to-device message to exclusive_as_user
  597. message_content = {"some_key": "some really interesting value"}
  598. chan = self.make_request(
  599. "PUT",
  600. "/_matrix/client/r0/sendToDevice/m.room_key_request/3",
  601. content={
  602. "messages": {
  603. self.exclusive_as_user: {
  604. self.exclusive_as_user_device_id: message_content
  605. }
  606. }
  607. },
  608. access_token=self.local_user_token,
  609. )
  610. self.assertEqual(chan.code, 200, chan.result)
  611. # Have exclusive_as_user send a to-device message to local_user
  612. chan = self.make_request(
  613. "PUT",
  614. "/_matrix/client/r0/sendToDevice/m.room_key_request/4",
  615. content={
  616. "messages": {
  617. self.local_user: {self.local_user_device_id: message_content}
  618. }
  619. },
  620. access_token=self.exclusive_as_user_token,
  621. )
  622. self.assertEqual(chan.code, 200, chan.result)
  623. # Check if our application service - that is interested in exclusive_as_user - received
  624. # the to-device message as part of an AS transaction.
  625. # Only the local_user -> exclusive_as_user to-device message should have been forwarded to the AS.
  626. #
  627. # The uninterested application service should not have been notified at all.
  628. self.send_mock.assert_called_once()
  629. (
  630. service,
  631. _events,
  632. _ephemeral,
  633. to_device_messages,
  634. _otks,
  635. _fbks,
  636. _device_list_summary,
  637. ) = self.send_mock.call_args[0]
  638. # Assert that this was the same to-device message that local_user sent
  639. self.assertEqual(service, interested_appservice)
  640. self.assertEqual(to_device_messages[0]["type"], "m.room_key_request")
  641. self.assertEqual(to_device_messages[0]["sender"], self.local_user)
  642. # Additional fields 'to_user_id' and 'to_device_id' specifically for
  643. # to-device messages via the AS API
  644. self.assertEqual(to_device_messages[0]["to_user_id"], self.exclusive_as_user)
  645. self.assertEqual(
  646. to_device_messages[0]["to_device_id"], self.exclusive_as_user_device_id
  647. )
  648. self.assertEqual(to_device_messages[0]["content"], message_content)
  649. @unittest.override_config(
  650. {"experimental_features": {"msc2409_to_device_messages_enabled": True}}
  651. )
  652. def test_application_services_receive_bursts_of_to_device(self) -> None:
  653. """
  654. Test that when a user sends >100 to-device messages at once, any
  655. interested AS's will receive them in separate transactions.
  656. Also tests that uninterested application services do not receive messages.
  657. """
  658. # Register two application services with exclusive interest in a user
  659. interested_appservices = []
  660. for _ in range(2):
  661. appservice = self._register_application_service(
  662. namespaces={
  663. ApplicationService.NS_USERS: [
  664. {
  665. "regex": "@exclusive_as_user:.+",
  666. "exclusive": True,
  667. }
  668. ],
  669. },
  670. )
  671. interested_appservices.append(appservice)
  672. # ...and an application service which does not have any user interest.
  673. self._register_application_service()
  674. to_device_message_content = {
  675. "some key": "some interesting value",
  676. }
  677. # We need to send a large burst of to-device messages. We also would like to
  678. # include them all in the same application service transaction so that we can
  679. # test large transactions.
  680. #
  681. # To do this, we can send a single to-device message to many user devices at
  682. # once.
  683. #
  684. # We insert number_of_messages - 1 messages into the database directly. We'll then
  685. # send a final to-device message to the real device, which will also kick off
  686. # an AS transaction (as just inserting messages into the DB won't).
  687. number_of_messages = 150
  688. fake_device_ids = [f"device_{num}" for num in range(number_of_messages - 1)]
  689. messages = {
  690. self.exclusive_as_user: {
  691. device_id: {
  692. "type": "test_to_device_message",
  693. "sender": "@some:sender",
  694. "content": to_device_message_content,
  695. }
  696. for device_id in fake_device_ids
  697. }
  698. }
  699. # Create a fake device per message. We can't send to-device messages to
  700. # a device that doesn't exist.
  701. self.get_success(
  702. self.hs.get_datastores().main.db_pool.simple_insert_many(
  703. desc="test_application_services_receive_burst_of_to_device",
  704. table="devices",
  705. keys=("user_id", "device_id"),
  706. values=[
  707. (
  708. self.exclusive_as_user,
  709. device_id,
  710. )
  711. for device_id in fake_device_ids
  712. ],
  713. )
  714. )
  715. # Seed the device_inbox table with our fake messages
  716. self.get_success(
  717. self.hs.get_datastores().main.add_messages_to_device_inbox(messages, {})
  718. )
  719. # Now have local_user send a final to-device message to exclusive_as_user. All unsent
  720. # to-device messages should be sent to any application services
  721. # interested in exclusive_as_user.
  722. chan = self.make_request(
  723. "PUT",
  724. "/_matrix/client/r0/sendToDevice/m.room_key_request/4",
  725. content={
  726. "messages": {
  727. self.exclusive_as_user: {
  728. self.exclusive_as_user_device_id: to_device_message_content
  729. }
  730. }
  731. },
  732. access_token=self.local_user_token,
  733. )
  734. self.assertEqual(chan.code, 200, chan.result)
  735. self.send_mock.assert_called()
  736. # Count the total number of to-device messages that were sent out per-service.
  737. # Ensure that we only sent to-device messages to interested services, and that
  738. # each interested service received the full count of to-device messages.
  739. service_id_to_message_count: Dict[str, int] = {}
  740. for call in self.send_mock.call_args_list:
  741. (
  742. service,
  743. _events,
  744. _ephemeral,
  745. to_device_messages,
  746. _otks,
  747. _fbks,
  748. _device_list_summary,
  749. ) = call[0]
  750. # Check that this was made to an interested service
  751. self.assertIn(service, interested_appservices)
  752. # Add to the count of messages for this application service
  753. service_id_to_message_count.setdefault(service.id, 0)
  754. service_id_to_message_count[service.id] += len(to_device_messages)
  755. # Assert that each interested service received the full count of messages
  756. for count in service_id_to_message_count.values():
  757. self.assertEqual(count, number_of_messages)
  758. def _register_application_service(
  759. self,
  760. namespaces: Optional[Dict[str, Iterable[Dict]]] = None,
  761. ) -> ApplicationService:
  762. """
  763. Register a new application service, with the given namespaces of interest.
  764. Args:
  765. namespaces: A dictionary containing any user, room or alias namespaces that
  766. the application service is interested in.
  767. Returns:
  768. The registered application service.
  769. """
  770. # Create an application service
  771. appservice = ApplicationService(
  772. token=random_string(10),
  773. id=random_string(10),
  774. sender="@as:example.com",
  775. rate_limited=False,
  776. namespaces=namespaces,
  777. supports_ephemeral=True,
  778. )
  779. # Register the application service
  780. self._services.append(appservice)
  781. return appservice
  782. class ApplicationServicesHandlerDeviceListsTestCase(unittest.HomeserverTestCase):
  783. """
  784. Tests that the ApplicationServicesHandler sends device list updates to application
  785. services correctly.
  786. """
  787. servlets = [
  788. synapse.rest.admin.register_servlets_for_client_rest_resource,
  789. login.register_servlets,
  790. room.register_servlets,
  791. ]
  792. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  793. # Allow us to modify cached feature flags mid-test
  794. self.as_handler = hs.get_application_service_handler()
  795. # Mock ApplicationServiceApi's put_json, so we can verify the raw JSON that
  796. # will be sent over the wire
  797. self.put_json = AsyncMock()
  798. hs.get_application_service_api().put_json = self.put_json # type: ignore[assignment]
  799. # Mock out application services, and allow defining our own in tests
  800. self._services: List[ApplicationService] = []
  801. self.hs.get_datastores().main.get_app_services = Mock( # type: ignore[assignment]
  802. return_value=self._services
  803. )
  804. # Test across a variety of configuration values
  805. @parameterized.expand(
  806. [
  807. (True, True, True),
  808. (True, False, False),
  809. (False, True, False),
  810. (False, False, False),
  811. ]
  812. )
  813. def test_application_service_receives_device_list_updates(
  814. self,
  815. experimental_feature_enabled: bool,
  816. as_supports_txn_extensions: bool,
  817. as_should_receive_device_list_updates: bool,
  818. ) -> None:
  819. """
  820. Tests that an application service receives notice of changed device
  821. lists for a user, when a user changes their device lists.
  822. Arguments above are populated by parameterized.
  823. Args:
  824. as_should_receive_device_list_updates: Whether we expect the AS to receive the
  825. device list changes.
  826. experimental_feature_enabled: Whether the "msc3202_transaction_extensions" experimental
  827. feature is enabled. This feature must be enabled for device lists to ASs to work.
  828. as_supports_txn_extensions: Whether the application service has explicitly registered
  829. to receive information defined by MSC3202 - which includes device list changes.
  830. """
  831. # Change whether the experimental feature is enabled or disabled before making
  832. # device list changes
  833. self.as_handler._msc3202_transaction_extensions_enabled = (
  834. experimental_feature_enabled
  835. )
  836. # Create an appservice that is interested in "local_user"
  837. appservice = ApplicationService(
  838. token=random_string(10),
  839. id=random_string(10),
  840. sender="@as:example.com",
  841. rate_limited=False,
  842. namespaces={
  843. ApplicationService.NS_USERS: [
  844. {
  845. "regex": "@local_user:.+",
  846. "exclusive": False,
  847. }
  848. ],
  849. },
  850. supports_ephemeral=True,
  851. msc3202_transaction_extensions=as_supports_txn_extensions,
  852. # Must be set for Synapse to try pushing data to the AS
  853. hs_token="abcde",
  854. url="some_url",
  855. )
  856. # Register the application service
  857. self._services.append(appservice)
  858. # Register a user on the homeserver
  859. self.local_user = self.register_user("local_user", "password")
  860. self.local_user_token = self.login("local_user", "password")
  861. if as_should_receive_device_list_updates:
  862. # Ensure that the resulting JSON uses the unstable prefix and contains the
  863. # expected users
  864. self.put_json.assert_called_once()
  865. json_body = self.put_json.call_args[1]["json_body"]
  866. # Our application service should have received a device list update with
  867. # "local_user" in the "changed" list
  868. device_list_dict = json_body.get("org.matrix.msc3202.device_lists", {})
  869. self.assertEqual([], device_list_dict["left"])
  870. self.assertEqual([self.local_user], device_list_dict["changed"])
  871. else:
  872. # No device list changes should have been sent out
  873. self.put_json.assert_not_called()
  874. class ApplicationServicesHandlerOtkCountsTestCase(unittest.HomeserverTestCase):
  875. # Argument indices for pulling out arguments from a `send_mock`.
  876. ARG_OTK_COUNTS = 4
  877. ARG_FALLBACK_KEYS = 5
  878. servlets = [
  879. synapse.rest.admin.register_servlets_for_client_rest_resource,
  880. login.register_servlets,
  881. register.register_servlets,
  882. room.register_servlets,
  883. sendtodevice.register_servlets,
  884. receipts.register_servlets,
  885. ]
  886. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  887. # Mock the ApplicationServiceScheduler's _TransactionController's send method so that
  888. # we can track what's going out
  889. self.send_mock = AsyncMock()
  890. hs.get_application_service_handler().scheduler.txn_ctrl.send = self.send_mock # type: ignore[assignment] # We assign to a method.
  891. # Define an application service for the tests
  892. self._service_token = "VERYSECRET"
  893. self._service = ApplicationService(
  894. self._service_token,
  895. "as1",
  896. "@as.sender:test",
  897. namespaces={
  898. "users": [
  899. {"regex": "@_as_.*:test", "exclusive": True},
  900. {"regex": "@as.sender:test", "exclusive": True},
  901. ]
  902. },
  903. msc3202_transaction_extensions=True,
  904. )
  905. self.hs.get_datastores().main.services_cache = [self._service]
  906. # Register some appservice users
  907. self._sender_user, self._sender_device = self.register_appservice_user(
  908. "as.sender", self._service_token
  909. )
  910. self._namespaced_user, self._namespaced_device = self.register_appservice_user(
  911. "_as_user1", self._service_token
  912. )
  913. # Register a real user as well.
  914. self._real_user = self.register_user("real.user", "meow")
  915. self._real_user_token = self.login("real.user", "meow")
  916. async def _add_otks_for_device(
  917. self, user_id: str, device_id: str, otk_count: int
  918. ) -> None:
  919. """
  920. Add some dummy keys. It doesn't matter if they're not a real algorithm;
  921. that should be opaque to the server anyway.
  922. """
  923. await self.hs.get_datastores().main.add_e2e_one_time_keys(
  924. user_id,
  925. device_id,
  926. self.clock.time_msec(),
  927. [("algo", f"k{i}", "{}") for i in range(otk_count)],
  928. )
  929. async def _add_fallback_key_for_device(
  930. self, user_id: str, device_id: str, used: bool
  931. ) -> None:
  932. """
  933. Adds a fake fallback key to a device, optionally marking it as used
  934. right away.
  935. """
  936. store = self.hs.get_datastores().main
  937. await store.set_e2e_fallback_keys(user_id, device_id, {"algo:fk": "fall back!"})
  938. if used is True:
  939. # Mark the key as used
  940. await store.db_pool.simple_update_one(
  941. table="e2e_fallback_keys_json",
  942. keyvalues={
  943. "user_id": user_id,
  944. "device_id": device_id,
  945. "algorithm": "algo",
  946. "key_id": "fk",
  947. },
  948. updatevalues={"used": True},
  949. desc="_get_fallback_key_set_used",
  950. )
  951. def _set_up_devices_and_a_room(self) -> str:
  952. """
  953. Helper to set up devices for all the users
  954. and a room for the users to talk in.
  955. """
  956. async def preparation() -> None:
  957. await self._add_otks_for_device(self._sender_user, self._sender_device, 42)
  958. await self._add_fallback_key_for_device(
  959. self._sender_user, self._sender_device, used=True
  960. )
  961. await self._add_otks_for_device(
  962. self._namespaced_user, self._namespaced_device, 36
  963. )
  964. await self._add_fallback_key_for_device(
  965. self._namespaced_user, self._namespaced_device, used=False
  966. )
  967. # Register a device for the real user, too, so that we can later ensure
  968. # that we don't leak information to the AS about the non-AS user.
  969. await self.hs.get_datastores().main.store_device(
  970. self._real_user, "REALDEV", "UltraMatrix 3000"
  971. )
  972. await self._add_otks_for_device(self._real_user, "REALDEV", 50)
  973. self.get_success(preparation())
  974. room_id = self.helper.create_room_as(
  975. self._real_user, is_public=True, tok=self._real_user_token
  976. )
  977. self.helper.join(
  978. room_id,
  979. self._namespaced_user,
  980. tok=self._service_token,
  981. appservice_user_id=self._namespaced_user,
  982. )
  983. # Check it was called for sanity. (This was to send the join event to the AS.)
  984. self.send_mock.assert_called()
  985. self.send_mock.reset_mock()
  986. return room_id
  987. @override_config(
  988. {"experimental_features": {"msc3202_transaction_extensions": True}}
  989. )
  990. def test_application_services_receive_otk_counts_and_fallback_key_usages_with_pdus(
  991. self,
  992. ) -> None:
  993. """
  994. Tests that:
  995. - the AS receives one-time key counts and unused fallback keys for:
  996. - the specified sender; and
  997. - any user who is in receipt of the PDUs
  998. """
  999. room_id = self._set_up_devices_and_a_room()
  1000. # Send a message into the AS's room
  1001. self.helper.send(room_id, "woof woof", tok=self._real_user_token)
  1002. # Capture what was sent as an AS transaction.
  1003. self.send_mock.assert_called()
  1004. last_args, _last_kwargs = self.send_mock.call_args
  1005. otks: Optional[TransactionOneTimeKeysCount] = last_args[self.ARG_OTK_COUNTS]
  1006. unused_fallbacks: Optional[TransactionUnusedFallbackKeys] = last_args[
  1007. self.ARG_FALLBACK_KEYS
  1008. ]
  1009. self.assertEqual(
  1010. otks,
  1011. {
  1012. "@as.sender:test": {self._sender_device: {"algo": 42}},
  1013. "@_as_user1:test": {self._namespaced_device: {"algo": 36}},
  1014. },
  1015. )
  1016. self.assertEqual(
  1017. unused_fallbacks,
  1018. {
  1019. "@as.sender:test": {self._sender_device: []},
  1020. "@_as_user1:test": {self._namespaced_device: ["algo"]},
  1021. },
  1022. )