1
0

test_message.py 13 KB

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