1
0

test_appservice.py 35 KB

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