test_message.py 7.6 KB

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