test_message.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import Tuple
  17. from synapse.api.constants import EventTypes
  18. from synapse.events import EventBase
  19. from synapse.events.snapshot import EventContext
  20. from synapse.rest import admin
  21. from synapse.rest.client.v1 import login, room
  22. from synapse.types import create_requester
  23. from synapse.util.stringutils import random_string
  24. from tests import unittest
  25. logger = logging.getLogger(__name__)
  26. class EventCreationTestCase(unittest.HomeserverTestCase):
  27. servlets = [
  28. admin.register_servlets,
  29. login.register_servlets,
  30. room.register_servlets,
  31. ]
  32. def prepare(self, reactor, clock, hs):
  33. self.handler = self.hs.get_event_creation_handler()
  34. self.persist_event_storage = self.hs.get_storage().persistence
  35. self.user_id = self.register_user("tester", "foobar")
  36. self.access_token = self.login("tester", "foobar")
  37. self.room_id = self.helper.create_room_as(self.user_id, tok=self.access_token)
  38. self.info = self.get_success(
  39. self.hs.get_datastore().get_user_by_access_token(
  40. self.access_token,
  41. )
  42. )
  43. self.token_id = self.info.token_id
  44. self.requester = create_requester(self.user_id, access_token_id=self.token_id)
  45. def _create_duplicate_event(self, txn_id: str) -> Tuple[EventBase, EventContext]:
  46. """Create a new event with the given transaction ID. All events produced
  47. by this method will be considered duplicates.
  48. """
  49. # We create a new event with a random body, as otherwise we'll produce
  50. # *exactly* the same event with the same hash, and so same event ID.
  51. return self.get_success(
  52. self.handler.create_event(
  53. self.requester,
  54. {
  55. "type": EventTypes.Message,
  56. "room_id": self.room_id,
  57. "sender": self.requester.user.to_string(),
  58. "content": {"msgtype": "m.text", "body": random_string(5)},
  59. },
  60. txn_id=txn_id,
  61. )
  62. )
  63. def test_duplicated_txn_id(self):
  64. """Test that attempting to handle/persist an event with a transaction ID
  65. that has already been persisted correctly returns the old event and does
  66. *not* produce duplicate messages.
  67. """
  68. txn_id = "something_suitably_random"
  69. event1, context = self._create_duplicate_event(txn_id)
  70. ret_event1 = self.get_success(
  71. self.handler.handle_new_client_event(self.requester, event1, context)
  72. )
  73. stream_id1 = ret_event1.internal_metadata.stream_ordering
  74. self.assertEqual(event1.event_id, ret_event1.event_id)
  75. event2, context = self._create_duplicate_event(txn_id)
  76. # We want to test that the deduplication at the persit event end works,
  77. # so we want to make sure we test with different events.
  78. self.assertNotEqual(event1.event_id, event2.event_id)
  79. ret_event2 = self.get_success(
  80. self.handler.handle_new_client_event(self.requester, event2, context)
  81. )
  82. stream_id2 = ret_event2.internal_metadata.stream_ordering
  83. # Assert that the returned values match those from the initial event
  84. # rather than the new one.
  85. self.assertEqual(ret_event1.event_id, ret_event2.event_id)
  86. self.assertEqual(stream_id1, stream_id2)
  87. # Let's test that calling `persist_event` directly also does the right
  88. # thing.
  89. event3, context = self._create_duplicate_event(txn_id)
  90. self.assertNotEqual(event1.event_id, event3.event_id)
  91. ret_event3, event_pos3, _ = self.get_success(
  92. self.persist_event_storage.persist_event(event3, context)
  93. )
  94. # Assert that the returned values match those from the initial event
  95. # rather than the new one.
  96. self.assertEqual(ret_event1.event_id, ret_event3.event_id)
  97. self.assertEqual(stream_id1, event_pos3.stream)
  98. # Let's test that calling `persist_events` directly also does the right
  99. # thing.
  100. event4, context = self._create_duplicate_event(txn_id)
  101. self.assertNotEqual(event1.event_id, event3.event_id)
  102. events, _ = self.get_success(
  103. self.persist_event_storage.persist_events([(event3, context)])
  104. )
  105. ret_event4 = events[0]
  106. # Assert that the returned values match those from the initial event
  107. # rather than the new one.
  108. self.assertEqual(ret_event1.event_id, ret_event4.event_id)
  109. def test_duplicated_txn_id_one_call(self):
  110. """Test that we correctly handle duplicates that we try and persist at
  111. the same time.
  112. """
  113. txn_id = "something_else_suitably_random"
  114. # Create two duplicate events to persist at the same time
  115. event1, context1 = self._create_duplicate_event(txn_id)
  116. event2, context2 = self._create_duplicate_event(txn_id)
  117. # Ensure their event IDs are different to start with
  118. self.assertNotEqual(event1.event_id, event2.event_id)
  119. events, _ = self.get_success(
  120. self.persist_event_storage.persist_events(
  121. [(event1, context1), (event2, context2)]
  122. )
  123. )
  124. # Check that we've deduplicated the events.
  125. self.assertEqual(len(events), 2)
  126. self.assertEqual(events[0].event_id, events[1].event_id)
  127. class ServerAclValidationTestCase(unittest.HomeserverTestCase):
  128. servlets = [
  129. admin.register_servlets,
  130. login.register_servlets,
  131. room.register_servlets,
  132. ]
  133. def prepare(self, reactor, clock, hs):
  134. self.user_id = self.register_user("tester", "foobar")
  135. self.access_token = self.login("tester", "foobar")
  136. self.room_id = self.helper.create_room_as(self.user_id, tok=self.access_token)
  137. def test_allow_server_acl(self):
  138. """Test that sending an ACL that blocks everyone but ourselves works."""
  139. self.helper.send_state(
  140. self.room_id,
  141. EventTypes.ServerACL,
  142. body={"allow": [self.hs.hostname]},
  143. tok=self.access_token,
  144. expect_code=200,
  145. )
  146. def test_deny_server_acl_block_outselves(self):
  147. """Test that sending an ACL that blocks ourselves does not work."""
  148. self.helper.send_state(
  149. self.room_id,
  150. EventTypes.ServerACL,
  151. body={},
  152. tok=self.access_token,
  153. expect_code=400,
  154. )
  155. def test_deny_redact_server_acl(self):
  156. """Test that attempting to redact an ACL is blocked."""
  157. body = self.helper.send_state(
  158. self.room_id,
  159. EventTypes.ServerACL,
  160. body={"allow": [self.hs.hostname]},
  161. tok=self.access_token,
  162. expect_code=200,
  163. )
  164. event_id = body["event_id"]
  165. # Redaction of event should fail.
  166. path = "/_matrix/client/r0/rooms/%s/redact/%s" % (self.room_id, event_id)
  167. channel = self.make_request(
  168. "POST", path, content={}, access_token=self.access_token
  169. )
  170. self.assertEqual(int(channel.result["code"]), 403)