You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1283 lines
49 KiB

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