test_message.py 13 KB

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