test_federation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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, LimitExceededError, 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. @unittest.override_config(
  162. {"rc_invites": {"per_user": {"per_second": 0.5, "burst_count": 3}}}
  163. )
  164. def test_invite_by_user_ratelimit(self):
  165. """Tests that invites from federation to a particular user are
  166. actually rate-limited.
  167. """
  168. other_server = "otherserver"
  169. other_user = "@otheruser:" + other_server
  170. # create the room
  171. user_id = self.register_user("kermit", "test")
  172. tok = self.login("kermit", "test")
  173. def create_invite():
  174. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  175. room_version = self.get_success(self.store.get_room_version(room_id))
  176. return event_from_pdu_json(
  177. {
  178. "type": EventTypes.Member,
  179. "content": {"membership": "invite"},
  180. "room_id": room_id,
  181. "sender": other_user,
  182. "state_key": "@user:test",
  183. "depth": 32,
  184. "prev_events": [],
  185. "auth_events": [],
  186. "origin_server_ts": self.clock.time_msec(),
  187. },
  188. room_version,
  189. )
  190. for i in range(3):
  191. event = create_invite()
  192. self.get_success(
  193. self.handler.on_invite_request(
  194. other_server,
  195. event,
  196. event.room_version,
  197. )
  198. )
  199. event = create_invite()
  200. self.get_failure(
  201. self.handler.on_invite_request(
  202. other_server,
  203. event,
  204. event.room_version,
  205. ),
  206. exc=LimitExceededError,
  207. )
  208. def _build_and_send_join_event(self, other_server, other_user, room_id):
  209. join_event = self.get_success(
  210. self.handler.on_make_join_request(other_server, room_id, other_user)
  211. )
  212. # the auth code requires that a signature exists, but doesn't check that
  213. # signature... go figure.
  214. join_event.signatures[other_server] = {"x": "y"}
  215. with LoggingContext("send_join"):
  216. d = run_in_background(
  217. self.handler.on_send_join_request, other_server, join_event
  218. )
  219. self.get_success(d)
  220. # sanity-check: the room should show that the new user is a member
  221. r = self.get_success(self.store.get_current_state_ids(room_id))
  222. self.assertEqual(r[(EventTypes.Member, other_user)], join_event.event_id)
  223. return join_event
  224. class EventFromPduTestCase(TestCase):
  225. def test_valid_json(self):
  226. """Valid JSON should be turned into an event."""
  227. ev = event_from_pdu_json(
  228. {
  229. "type": EventTypes.Message,
  230. "content": {"bool": True, "null": None, "int": 1, "str": "foobar"},
  231. "room_id": "!room:test",
  232. "sender": "@user:test",
  233. "depth": 1,
  234. "prev_events": [],
  235. "auth_events": [],
  236. "origin_server_ts": 1234,
  237. },
  238. RoomVersions.V6,
  239. )
  240. self.assertIsInstance(ev, EventBase)
  241. def test_invalid_numbers(self):
  242. """Invalid values for an integer should be rejected, all floats should be rejected."""
  243. for value in [
  244. -(2 ** 53),
  245. 2 ** 53,
  246. 1.0,
  247. float("inf"),
  248. float("-inf"),
  249. float("nan"),
  250. ]:
  251. with self.assertRaises(SynapseError):
  252. event_from_pdu_json(
  253. {
  254. "type": EventTypes.Message,
  255. "content": {"foo": value},
  256. "room_id": "!room:test",
  257. "sender": "@user:test",
  258. "depth": 1,
  259. "prev_events": [],
  260. "auth_events": [],
  261. "origin_server_ts": 1234,
  262. },
  263. RoomVersions.V6,
  264. )
  265. def test_invalid_nested(self):
  266. """List and dictionaries are recursively searched."""
  267. with self.assertRaises(SynapseError):
  268. event_from_pdu_json(
  269. {
  270. "type": EventTypes.Message,
  271. "content": {"foo": [{"bar": 2 ** 56}]},
  272. "room_id": "!room:test",
  273. "sender": "@user:test",
  274. "depth": 1,
  275. "prev_events": [],
  276. "auth_events": [],
  277. "origin_server_ts": 1234,
  278. },
  279. RoomVersions.V6,
  280. )