test_message.py 12 KB

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