test_message.py 12 KB

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