|
1 | | -# Copyright 2015, 2016 OpenMarket Ltd |
| 1 | +# Copyright 2015-2021 The Matrix.org Foundation C.I.C. |
2 | 2 | # |
3 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
4 | 4 | # you may not use this file except in compliance with the License. |
|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 |
|
| 15 | +from typing import Dict, Iterable, List, Optional, Tuple |
15 | 16 | from unittest.mock import Mock |
16 | 17 |
|
17 | 18 | from twisted.internet import defer |
18 | 19 |
|
| 20 | +import synapse.rest.admin |
| 21 | +import synapse.storage |
| 22 | +from synapse.appservice import ApplicationService |
19 | 23 | from synapse.handlers.appservice import ApplicationServicesHandler |
| 24 | +from synapse.rest.client import login, receipts, room, sendtodevice |
20 | 25 | from synapse.types import RoomStreamToken |
| 26 | +from synapse.util.stringutils import random_string |
21 | 27 |
|
| 28 | +from tests import unittest |
22 | 29 | from tests.test_utils import make_awaitable |
23 | 30 | from tests.utils import MockClock |
24 | 31 |
|
25 | | -from .. import unittest |
26 | | - |
27 | 32 |
|
28 | 33 | class AppServiceHandlerTestCase(unittest.TestCase): |
29 | 34 | """Tests the ApplicationServicesHandler.""" |
@@ -261,7 +266,6 @@ def test_notify_interested_services_ephemeral(self): |
261 | 266 | """ |
262 | 267 | interested_service = self._mkservice(is_interested=True) |
263 | 268 | services = [interested_service] |
264 | | - |
265 | 269 | self.mock_store.get_app_services.return_value = services |
266 | 270 | self.mock_store.get_type_stream_id_for_appservice.return_value = make_awaitable( |
267 | 271 | 579 |
@@ -321,3 +325,241 @@ def _mkservice_alias(self, is_interested_in_alias): |
321 | 325 | service.token = "mock_service_token" |
322 | 326 | service.url = "mock_service_url" |
323 | 327 | return service |
| 328 | + |
| 329 | + |
| 330 | +class ApplicationServiceEphemeralEventsTestCase(unittest.HomeserverTestCase): |
| 331 | + servlets = [ |
| 332 | + synapse.rest.admin.register_servlets_for_client_rest_resource, |
| 333 | + login.register_servlets, |
| 334 | + room.register_servlets, |
| 335 | + sendtodevice.register_servlets, |
| 336 | + receipts.register_servlets, |
| 337 | + ] |
| 338 | + |
| 339 | + def prepare(self, reactor, clock, hs): |
| 340 | + # Mock the application service scheduler so that we can track any |
| 341 | + # outgoing transactions |
| 342 | + self.mock_scheduler = Mock() |
| 343 | + self.mock_scheduler.submit_ephemeral_events_for_as = Mock() |
| 344 | + |
| 345 | + hs.get_application_service_handler().scheduler = self.mock_scheduler |
| 346 | + |
| 347 | + self.device1 = "device1" |
| 348 | + self.user1 = self.register_user("user1", "password") |
| 349 | + self.token1 = self.login("user1", "password", self.device1) |
| 350 | + |
| 351 | + self.device2 = "device2" |
| 352 | + self.user2 = self.register_user("user2", "password") |
| 353 | + self.token2 = self.login("user2", "password", self.device2) |
| 354 | + |
| 355 | + @unittest.override_config( |
| 356 | + {"experimental_features": {"msc2409_to_device_messages_enabled": True}} |
| 357 | + ) |
| 358 | + def test_application_services_receive_local_to_device(self): |
| 359 | + """ |
| 360 | + Test that when a user sends a to-device message to another user, and |
| 361 | + that is in an application service's user namespace, that application |
| 362 | + service will receive it. |
| 363 | + """ |
| 364 | + ( |
| 365 | + interested_services, |
| 366 | + _, |
| 367 | + ) = self._register_interested_and_uninterested_application_services() |
| 368 | + interested_service = interested_services[0] |
| 369 | + |
| 370 | + # Have user1 send a to-device message to user2 |
| 371 | + message_content = {"some_key": "some really interesting value"} |
| 372 | + chan = self.make_request( |
| 373 | + "PUT", |
| 374 | + "/_matrix/client/r0/sendToDevice/m.room_key_request/3", |
| 375 | + content={"messages": {self.user2: {self.device2: message_content}}}, |
| 376 | + access_token=self.token1, |
| 377 | + ) |
| 378 | + self.assertEqual(chan.code, 200, chan.result) |
| 379 | + |
| 380 | + # Have user2 send a to-device message to user1 |
| 381 | + chan = self.make_request( |
| 382 | + "PUT", |
| 383 | + "/_matrix/client/r0/sendToDevice/m.room_key_request/4", |
| 384 | + content={"messages": {self.user1: {self.device1: message_content}}}, |
| 385 | + access_token=self.token2, |
| 386 | + ) |
| 387 | + self.assertEqual(chan.code, 200, chan.result) |
| 388 | + |
| 389 | + # Check if our application service - that is interested in user2 - received |
| 390 | + # the to-device message as part of an AS transaction. |
| 391 | + # Only the user1 -> user2 to-device message should have been forwarded to the AS. |
| 392 | + # |
| 393 | + # The uninterested application service should not have been notified at all. |
| 394 | + self.assertEqual( |
| 395 | + 1, self.mock_scheduler.submit_ephemeral_events_for_as.call_count |
| 396 | + ) |
| 397 | + service, events = self.mock_scheduler.submit_ephemeral_events_for_as.call_args[ |
| 398 | + 0 |
| 399 | + ] |
| 400 | + |
| 401 | + # Assert that this was the same to-device message that user1 sent |
| 402 | + self.assertEqual(service, interested_service) |
| 403 | + self.assertEqual(events[0]["type"], "m.room_key_request") |
| 404 | + self.assertEqual(events[0]["sender"], self.user1) |
| 405 | + |
| 406 | + # Additional fields 'to_user_id' and 'to_device_id' specifically for |
| 407 | + # to-device messages via the AS API |
| 408 | + self.assertEqual(events[0]["to_user_id"], self.user2) |
| 409 | + self.assertEqual(events[0]["to_device_id"], self.device2) |
| 410 | + self.assertEqual(events[0]["content"], message_content) |
| 411 | + |
| 412 | + @unittest.override_config( |
| 413 | + {"experimental_features": {"msc2409_to_device_messages_enabled": True}} |
| 414 | + ) |
| 415 | + def test_application_services_receive_bursts_of_to_device(self): |
| 416 | + """ |
| 417 | + Test that when a user sends >100 to-device messages at once, any |
| 418 | + interested AS's will receive them in separate transactions. |
| 419 | + """ |
| 420 | + ( |
| 421 | + interested_services, |
| 422 | + _, |
| 423 | + ) = self._register_interested_and_uninterested_application_services( |
| 424 | + interested_count=2, |
| 425 | + uninterested_count=2, |
| 426 | + ) |
| 427 | + |
| 428 | + to_device_message_content = { |
| 429 | + "some key": "some interesting value", |
| 430 | + } |
| 431 | + |
| 432 | + # We need to send a large burst of to-device messages. We also would like to |
| 433 | + # include them all in the same application service transaction so that we can |
| 434 | + # test large transactions. |
| 435 | + # |
| 436 | + # To do this, we can send a single to-device message to many user devices at |
| 437 | + # once. |
| 438 | + # |
| 439 | + # We insert number_of_messages - 1 messages into the database directly. We'll then |
| 440 | + # send a final to-device message to the real device, which will also kick off |
| 441 | + # an AS transaction (as just inserting messages into the DB won't). |
| 442 | + number_of_messages = 150 |
| 443 | + fake_device_ids = [f"device_{num}" for num in range(number_of_messages - 1)] |
| 444 | + messages = { |
| 445 | + self.user2: { |
| 446 | + device_id: to_device_message_content for device_id in fake_device_ids |
| 447 | + } |
| 448 | + } |
| 449 | + |
| 450 | + # Create a fake device per message. We can't send to-device messages to |
| 451 | + # a device that doesn't exist. |
| 452 | + self.get_success( |
| 453 | + self.hs.get_datastore().db_pool.simple_insert_many( |
| 454 | + desc="test_application_services_receive_burst_of_to_device", |
| 455 | + table="devices", |
| 456 | + values=[ |
| 457 | + { |
| 458 | + "user_id": self.user2, |
| 459 | + "device_id": device_id, |
| 460 | + } |
| 461 | + for device_id in fake_device_ids |
| 462 | + ], |
| 463 | + ) |
| 464 | + ) |
| 465 | + |
| 466 | + # Seed the device_inbox table with our fake messages |
| 467 | + self.get_success( |
| 468 | + self.hs.get_datastore().add_messages_to_device_inbox(messages, {}) |
| 469 | + ) |
| 470 | + |
| 471 | + # Now have user1 send a final to-device message to user2. All unsent |
| 472 | + # to-device messages should be sent to any application services |
| 473 | + # interested in user2. |
| 474 | + chan = self.make_request( |
| 475 | + "PUT", |
| 476 | + "/_matrix/client/r0/sendToDevice/m.room_key_request/4", |
| 477 | + content={ |
| 478 | + "messages": {self.user2: {self.device2: to_device_message_content}} |
| 479 | + }, |
| 480 | + access_token=self.token1, |
| 481 | + ) |
| 482 | + self.assertEqual(chan.code, 200, chan.result) |
| 483 | + |
| 484 | + # Count the total number of to-device messages that were sent out per-service. |
| 485 | + # Ensure that we only sent to-device messages to interested services, and that |
| 486 | + # each interested service received the full count of to-device messages. |
| 487 | + service_id_to_message_count: Dict[str, int] = {} |
| 488 | + self.assertGreater( |
| 489 | + self.mock_scheduler.submit_ephemeral_events_for_as.call_count, 0 |
| 490 | + ) |
| 491 | + for call in self.mock_scheduler.submit_ephemeral_events_for_as.call_args_list: |
| 492 | + service, events = call[0] |
| 493 | + |
| 494 | + # Check that this was made to an interested service |
| 495 | + self.assertIn(service, interested_services) |
| 496 | + |
| 497 | + # Add to the count of messages for this application service |
| 498 | + service_id_to_message_count.setdefault(service.id, 0) |
| 499 | + service_id_to_message_count[service.id] += len(events) |
| 500 | + |
| 501 | + # Assert that each interested service received the full count of messages |
| 502 | + for count in service_id_to_message_count.values(): |
| 503 | + self.assertEqual(count, number_of_messages) |
| 504 | + |
| 505 | + def _register_interested_and_uninterested_application_services( |
| 506 | + self, |
| 507 | + interested_count: int = 1, |
| 508 | + uninterested_count: int = 1, |
| 509 | + ) -> Tuple[List[ApplicationService], List[ApplicationService]]: |
| 510 | + """ |
| 511 | + Create application services with and without exclusive interest |
| 512 | + in user2. |
| 513 | +
|
| 514 | + Args: |
| 515 | + interested_count: The number of application services to create |
| 516 | + and register with exclusive interest. |
| 517 | + uninterested_count: The number of application services to create |
| 518 | + and register without any interest. |
| 519 | +
|
| 520 | + Returns: |
| 521 | + A two-tuple containing: |
| 522 | + * Interested application services |
| 523 | + * Uninterested application services |
| 524 | + """ |
| 525 | + # Create an application service with exclusive interest in user2 |
| 526 | + interested_services = [] |
| 527 | + uninterested_services = [] |
| 528 | + for _ in range(interested_count): |
| 529 | + interested_service = self._make_application_service( |
| 530 | + namespaces={ |
| 531 | + ApplicationService.NS_USERS: [ |
| 532 | + { |
| 533 | + "regex": "@user2:.+", |
| 534 | + "exclusive": True, |
| 535 | + } |
| 536 | + ], |
| 537 | + }, |
| 538 | + ) |
| 539 | + interested_services.append(interested_service) |
| 540 | + |
| 541 | + for _ in range(uninterested_count): |
| 542 | + uninterested_services.append(self._make_application_service()) |
| 543 | + |
| 544 | + # Register this application service, along with another, uninterested one |
| 545 | + services = [ |
| 546 | + *uninterested_services, |
| 547 | + *interested_services, |
| 548 | + ] |
| 549 | + self.hs.get_datastore().get_app_services = Mock(return_value=services) |
| 550 | + |
| 551 | + return interested_services, uninterested_services |
| 552 | + |
| 553 | + def _make_application_service( |
| 554 | + self, |
| 555 | + namespaces: Optional[Dict[str, Iterable[Dict]]] = None, |
| 556 | + ) -> ApplicationService: |
| 557 | + return ApplicationService( |
| 558 | + token=None, |
| 559 | + hostname="example.com", |
| 560 | + id=random_string(10), |
| 561 | + sender="@as:example.com", |
| 562 | + rate_limited=False, |
| 563 | + namespaces=namespaces, |
| 564 | + supports_ephemeral=True, |
| 565 | + ) |
0 commit comments