test_message.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 import login, room
  21. from synapse.types import create_requester
  22. from synapse.util.stringutils import random_string
  23. from tests import unittest
  24. from tests.test_utils.event_injection import create_event
  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_controller = (
  35. self.hs.get_storage_controllers().persistence
  36. )
  37. self.user_id = self.register_user("tester", "foobar")
  38. self.access_token = self.login("tester", "foobar")
  39. self.room_id = self.helper.create_room_as(self.user_id, tok=self.access_token)
  40. self.info = self.get_success(
  41. self.hs.get_datastores().main.get_user_by_access_token(
  42. self.access_token,
  43. )
  44. )
  45. self.token_id = self.info.token_id
  46. self.requester = create_requester(self.user_id, access_token_id=self.token_id)
  47. def _create_and_persist_member_event(self) -> Tuple[EventBase, EventContext]:
  48. # Create a member event we can use as an auth_event
  49. memberEvent, memberEventContext = self.get_success(
  50. create_event(
  51. self.hs,
  52. room_id=self.room_id,
  53. type="m.room.member",
  54. sender=self.requester.user.to_string(),
  55. state_key=self.requester.user.to_string(),
  56. content={"membership": "join"},
  57. )
  58. )
  59. self.get_success(
  60. self._persist_event_storage_controller.persist_event(
  61. memberEvent, memberEventContext
  62. )
  63. )
  64. return memberEvent, memberEventContext
  65. def _create_duplicate_event(self, txn_id: str) -> Tuple[EventBase, EventContext]:
  66. """Create a new event with the given transaction ID. All events produced
  67. by this method will be considered duplicates.
  68. """
  69. # We create a new event with a random body, as otherwise we'll produce
  70. # *exactly* the same event with the same hash, and so same event ID.
  71. return self.get_success(
  72. self.handler.create_event(
  73. self.requester,
  74. {
  75. "type": EventTypes.Message,
  76. "room_id": self.room_id,
  77. "sender": self.requester.user.to_string(),
  78. "content": {"msgtype": "m.text", "body": random_string(5)},
  79. },
  80. txn_id=txn_id,
  81. )
  82. )
  83. def test_duplicated_txn_id(self):
  84. """Test that attempting to handle/persist an event with a transaction ID
  85. that has already been persisted correctly returns the old event and does
  86. *not* produce duplicate messages.
  87. """
  88. txn_id = "something_suitably_random"
  89. event1, context = self._create_duplicate_event(txn_id)
  90. ret_event1 = self.get_success(
  91. self.handler.handle_new_client_event(self.requester, event1, context)
  92. )
  93. stream_id1 = ret_event1.internal_metadata.stream_ordering
  94. self.assertEqual(event1.event_id, ret_event1.event_id)
  95. event2, context = self._create_duplicate_event(txn_id)
  96. # We want to test that the deduplication at the persit event end works,
  97. # so we want to make sure we test with different events.
  98. self.assertNotEqual(event1.event_id, event2.event_id)
  99. ret_event2 = self.get_success(
  100. self.handler.handle_new_client_event(self.requester, event2, context)
  101. )
  102. stream_id2 = ret_event2.internal_metadata.stream_ordering
  103. # Assert that the returned values match those from the initial event
  104. # rather than the new one.
  105. self.assertEqual(ret_event1.event_id, ret_event2.event_id)
  106. self.assertEqual(stream_id1, stream_id2)
  107. # Let's test that calling `persist_event` directly also does the right
  108. # thing.
  109. event3, context = self._create_duplicate_event(txn_id)
  110. self.assertNotEqual(event1.event_id, event3.event_id)
  111. ret_event3, event_pos3, _ = self.get_success(
  112. self._persist_event_storage_controller.persist_event(event3, context)
  113. )
  114. # Assert that the returned values match those from the initial event
  115. # rather than the new one.
  116. self.assertEqual(ret_event1.event_id, ret_event3.event_id)
  117. self.assertEqual(stream_id1, event_pos3.stream)
  118. # Let's test that calling `persist_events` directly also does the right
  119. # thing.
  120. event4, context = self._create_duplicate_event(txn_id)
  121. self.assertNotEqual(event1.event_id, event3.event_id)
  122. events, _ = self.get_success(
  123. self._persist_event_storage_controller.persist_events([(event3, context)])
  124. )
  125. ret_event4 = events[0]
  126. # Assert that the returned values match those from the initial event
  127. # rather than the new one.
  128. self.assertEqual(ret_event1.event_id, ret_event4.event_id)
  129. def test_duplicated_txn_id_one_call(self):
  130. """Test that we correctly handle duplicates that we try and persist at
  131. the same time.
  132. """
  133. txn_id = "something_else_suitably_random"
  134. # Create two duplicate events to persist at the same time
  135. event1, context1 = self._create_duplicate_event(txn_id)
  136. event2, context2 = self._create_duplicate_event(txn_id)
  137. # Ensure their event IDs are different to start with
  138. self.assertNotEqual(event1.event_id, event2.event_id)
  139. events, _ = self.get_success(
  140. self._persist_event_storage_controller.persist_events(
  141. [(event1, context1), (event2, context2)]
  142. )
  143. )
  144. # Check that we've deduplicated the events.
  145. self.assertEqual(len(events), 2)
  146. self.assertEqual(events[0].event_id, events[1].event_id)
  147. def test_when_empty_prev_events_allowed_create_event_with_empty_prev_events(self):
  148. """When we set allow_no_prev_events=True, should be able to create a
  149. event without any prev_events (only auth_events).
  150. """
  151. # Create a member event we can use as an auth_event
  152. memberEvent, _ = self._create_and_persist_member_event()
  153. # Try to create the event with empty prev_events bit with some auth_events
  154. event, _ = self.get_success(
  155. self.handler.create_event(
  156. self.requester,
  157. {
  158. "type": EventTypes.Message,
  159. "room_id": self.room_id,
  160. "sender": self.requester.user.to_string(),
  161. "content": {"msgtype": "m.text", "body": random_string(5)},
  162. },
  163. # Empty prev_events is the key thing we're testing here
  164. prev_event_ids=[],
  165. # But with some auth_events
  166. auth_event_ids=[memberEvent.event_id],
  167. # Allow no prev_events!
  168. allow_no_prev_events=True,
  169. )
  170. )
  171. self.assertIsNotNone(event)
  172. def test_when_empty_prev_events_not_allowed_reject_event_with_empty_prev_events(
  173. self,
  174. ):
  175. """When we set allow_no_prev_events=False, shouldn't be able to create a
  176. event without any prev_events even if it has auth_events. Expect an
  177. exception to be raised.
  178. """
  179. # Create a member event we can use as an auth_event
  180. memberEvent, _ = self._create_and_persist_member_event()
  181. # Try to create the event with empty prev_events but with some auth_events
  182. self.get_failure(
  183. self.handler.create_event(
  184. self.requester,
  185. {
  186. "type": EventTypes.Message,
  187. "room_id": self.room_id,
  188. "sender": self.requester.user.to_string(),
  189. "content": {"msgtype": "m.text", "body": random_string(5)},
  190. },
  191. # Empty prev_events is the key thing we're testing here
  192. prev_event_ids=[],
  193. # But with some auth_events
  194. auth_event_ids=[memberEvent.event_id],
  195. # We expect the test to fail because empty prev_events are not
  196. # allowed here!
  197. allow_no_prev_events=False,
  198. ),
  199. AssertionError,
  200. )
  201. def test_when_empty_prev_events_allowed_reject_event_with_empty_prev_events_and_auth_events(
  202. self,
  203. ):
  204. """When we set allow_no_prev_events=True, should be able to create a
  205. event without any prev_events or auth_events. Expect an exception to be
  206. raised.
  207. """
  208. # Try to create the event with empty prev_events and empty auth_events
  209. self.get_failure(
  210. self.handler.create_event(
  211. self.requester,
  212. {
  213. "type": EventTypes.Message,
  214. "room_id": self.room_id,
  215. "sender": self.requester.user.to_string(),
  216. "content": {"msgtype": "m.text", "body": random_string(5)},
  217. },
  218. prev_event_ids=[],
  219. # The event should be rejected when there are no auth_events
  220. auth_event_ids=[],
  221. # Allow no prev_events!
  222. allow_no_prev_events=True,
  223. ),
  224. AssertionError,
  225. )
  226. class ServerAclValidationTestCase(unittest.HomeserverTestCase):
  227. servlets = [
  228. admin.register_servlets,
  229. login.register_servlets,
  230. room.register_servlets,
  231. ]
  232. def prepare(self, reactor, clock, hs):
  233. self.user_id = self.register_user("tester", "foobar")
  234. self.access_token = self.login("tester", "foobar")
  235. self.room_id = self.helper.create_room_as(self.user_id, tok=self.access_token)
  236. def test_allow_server_acl(self):
  237. """Test that sending an ACL that blocks everyone but ourselves works."""
  238. self.helper.send_state(
  239. self.room_id,
  240. EventTypes.ServerACL,
  241. body={"allow": [self.hs.hostname]},
  242. tok=self.access_token,
  243. expect_code=200,
  244. )
  245. def test_deny_server_acl_block_outselves(self):
  246. """Test that sending an ACL that blocks ourselves does not work."""
  247. self.helper.send_state(
  248. self.room_id,
  249. EventTypes.ServerACL,
  250. body={},
  251. tok=self.access_token,
  252. expect_code=400,
  253. )
  254. def test_deny_redact_server_acl(self):
  255. """Test that attempting to redact an ACL is blocked."""
  256. body = self.helper.send_state(
  257. self.room_id,
  258. EventTypes.ServerACL,
  259. body={"allow": [self.hs.hostname]},
  260. tok=self.access_token,
  261. expect_code=200,
  262. )
  263. event_id = body["event_id"]
  264. # Redaction of event should fail.
  265. path = "/_matrix/client/r0/rooms/%s/redact/%s" % (self.room_id, event_id)
  266. channel = self.make_request(
  267. "POST", path, content={}, access_token=self.access_token
  268. )
  269. self.assertEqual(channel.code, 403)