test_federation.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from unittest import TestCase
  17. from synapse.api.constants import EventTypes
  18. from synapse.api.errors import AuthError, Codes, SynapseError
  19. from synapse.api.room_versions import RoomVersions
  20. from synapse.events import EventBase
  21. from synapse.federation.federation_base import event_from_pdu_json
  22. from synapse.logging.context import LoggingContext, run_in_background
  23. from synapse.rest import admin
  24. from synapse.rest.client.v1 import login, room
  25. from tests import unittest
  26. logger = logging.getLogger(__name__)
  27. class FederationTestCase(unittest.HomeserverTestCase):
  28. servlets = [
  29. admin.register_servlets,
  30. login.register_servlets,
  31. room.register_servlets,
  32. ]
  33. def make_homeserver(self, reactor, clock):
  34. hs = self.setup_test_homeserver(federation_http_client=None)
  35. self.handler = hs.get_federation_handler()
  36. self.store = hs.get_datastore()
  37. return hs
  38. def test_exchange_revoked_invite(self):
  39. user_id = self.register_user("kermit", "test")
  40. tok = self.login("kermit", "test")
  41. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  42. # Send a 3PID invite event with an empty body so it's considered as a revoked one.
  43. invite_token = "sometoken"
  44. self.helper.send_state(
  45. room_id=room_id,
  46. event_type=EventTypes.ThirdPartyInvite,
  47. state_key=invite_token,
  48. body={},
  49. tok=tok,
  50. )
  51. d = self.handler.on_exchange_third_party_invite_request(
  52. event_dict={
  53. "type": EventTypes.Member,
  54. "room_id": room_id,
  55. "sender": user_id,
  56. "state_key": "@someone:example.org",
  57. "content": {
  58. "membership": "invite",
  59. "third_party_invite": {
  60. "display_name": "alice",
  61. "signed": {
  62. "mxid": "@alice:localhost",
  63. "token": invite_token,
  64. "signatures": {
  65. "magic.forest": {
  66. "ed25519:3": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg"
  67. }
  68. },
  69. },
  70. },
  71. },
  72. },
  73. )
  74. failure = self.get_failure(d, AuthError).value
  75. self.assertEqual(failure.code, 403, failure)
  76. self.assertEqual(failure.errcode, Codes.FORBIDDEN, failure)
  77. self.assertEqual(failure.msg, "You are not invited to this room.")
  78. def test_rejected_message_event_state(self):
  79. """
  80. Check that we store the state group correctly for rejected non-state events.
  81. Regression test for #6289.
  82. """
  83. OTHER_SERVER = "otherserver"
  84. OTHER_USER = "@otheruser:" + OTHER_SERVER
  85. # create the room
  86. user_id = self.register_user("kermit", "test")
  87. tok = self.login("kermit", "test")
  88. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  89. room_version = self.get_success(self.store.get_room_version(room_id))
  90. # pretend that another server has joined
  91. join_event = self._build_and_send_join_event(OTHER_SERVER, OTHER_USER, room_id)
  92. # check the state group
  93. sg = self.successResultOf(
  94. self.store._get_state_group_for_event(join_event.event_id)
  95. )
  96. # build and send an event which will be rejected
  97. ev = event_from_pdu_json(
  98. {
  99. "type": EventTypes.Message,
  100. "content": {},
  101. "room_id": room_id,
  102. "sender": "@yetanotheruser:" + OTHER_SERVER,
  103. "depth": join_event["depth"] + 1,
  104. "prev_events": [join_event.event_id],
  105. "auth_events": [],
  106. "origin_server_ts": self.clock.time_msec(),
  107. },
  108. room_version,
  109. )
  110. with LoggingContext("send_rejected"):
  111. d = run_in_background(self.handler.on_receive_pdu, OTHER_SERVER, ev)
  112. self.get_success(d)
  113. # that should have been rejected
  114. e = self.get_success(self.store.get_event(ev.event_id, allow_rejected=True))
  115. self.assertIsNotNone(e.rejected_reason)
  116. # ... and the state group should be the same as before
  117. sg2 = self.successResultOf(self.store._get_state_group_for_event(ev.event_id))
  118. self.assertEqual(sg, sg2)
  119. def test_rejected_state_event_state(self):
  120. """
  121. Check that we store the state group correctly for rejected state events.
  122. Regression test for #6289.
  123. """
  124. OTHER_SERVER = "otherserver"
  125. OTHER_USER = "@otheruser:" + OTHER_SERVER
  126. # create the room
  127. user_id = self.register_user("kermit", "test")
  128. tok = self.login("kermit", "test")
  129. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  130. room_version = self.get_success(self.store.get_room_version(room_id))
  131. # pretend that another server has joined
  132. join_event = self._build_and_send_join_event(OTHER_SERVER, OTHER_USER, room_id)
  133. # check the state group
  134. sg = self.successResultOf(
  135. self.store._get_state_group_for_event(join_event.event_id)
  136. )
  137. # build and send an event which will be rejected
  138. ev = event_from_pdu_json(
  139. {
  140. "type": "org.matrix.test",
  141. "state_key": "test_key",
  142. "content": {},
  143. "room_id": room_id,
  144. "sender": "@yetanotheruser:" + OTHER_SERVER,
  145. "depth": join_event["depth"] + 1,
  146. "prev_events": [join_event.event_id],
  147. "auth_events": [],
  148. "origin_server_ts": self.clock.time_msec(),
  149. },
  150. room_version,
  151. )
  152. with LoggingContext("send_rejected"):
  153. d = run_in_background(self.handler.on_receive_pdu, OTHER_SERVER, ev)
  154. self.get_success(d)
  155. # that should have been rejected
  156. e = self.get_success(self.store.get_event(ev.event_id, allow_rejected=True))
  157. self.assertIsNotNone(e.rejected_reason)
  158. # ... and the state group should be the same as before
  159. sg2 = self.successResultOf(self.store._get_state_group_for_event(ev.event_id))
  160. self.assertEqual(sg, sg2)
  161. def _build_and_send_join_event(self, other_server, other_user, room_id):
  162. join_event = self.get_success(
  163. self.handler.on_make_join_request(other_server, room_id, other_user)
  164. )
  165. # the auth code requires that a signature exists, but doesn't check that
  166. # signature... go figure.
  167. join_event.signatures[other_server] = {"x": "y"}
  168. with LoggingContext("send_join"):
  169. d = run_in_background(
  170. self.handler.on_send_join_request, other_server, join_event
  171. )
  172. self.get_success(d)
  173. # sanity-check: the room should show that the new user is a member
  174. r = self.get_success(self.store.get_current_state_ids(room_id))
  175. self.assertEqual(r[(EventTypes.Member, other_user)], join_event.event_id)
  176. return join_event
  177. class EventFromPduTestCase(TestCase):
  178. def test_valid_json(self):
  179. """Valid JSON should be turned into an event."""
  180. ev = event_from_pdu_json(
  181. {
  182. "type": EventTypes.Message,
  183. "content": {"bool": True, "null": None, "int": 1, "str": "foobar"},
  184. "room_id": "!room:test",
  185. "sender": "@user:test",
  186. "depth": 1,
  187. "prev_events": [],
  188. "auth_events": [],
  189. "origin_server_ts": 1234,
  190. },
  191. RoomVersions.V6,
  192. )
  193. self.assertIsInstance(ev, EventBase)
  194. def test_invalid_numbers(self):
  195. """Invalid values for an integer should be rejected, all floats should be rejected."""
  196. for value in [
  197. -(2 ** 53),
  198. 2 ** 53,
  199. 1.0,
  200. float("inf"),
  201. float("-inf"),
  202. float("nan"),
  203. ]:
  204. with self.assertRaises(SynapseError):
  205. event_from_pdu_json(
  206. {
  207. "type": EventTypes.Message,
  208. "content": {"foo": value},
  209. "room_id": "!room:test",
  210. "sender": "@user:test",
  211. "depth": 1,
  212. "prev_events": [],
  213. "auth_events": [],
  214. "origin_server_ts": 1234,
  215. },
  216. RoomVersions.V6,
  217. )
  218. def test_invalid_nested(self):
  219. """List and dictionaries are recursively searched."""
  220. with self.assertRaises(SynapseError):
  221. event_from_pdu_json(
  222. {
  223. "type": EventTypes.Message,
  224. "content": {"foo": [{"bar": 2 ** 56}]},
  225. "room_id": "!room:test",
  226. "sender": "@user:test",
  227. "depth": 1,
  228. "prev_events": [],
  229. "auth_events": [],
  230. "origin_server_ts": 1234,
  231. },
  232. RoomVersions.V6,
  233. )