test_federation.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. # Copyright 2019 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 cast
  16. from unittest import TestCase
  17. from unittest.mock import Mock, patch
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.api.constants import EventTypes
  20. from synapse.api.errors import AuthError, Codes, LimitExceededError, SynapseError
  21. from synapse.api.room_versions import RoomVersions
  22. from synapse.events import EventBase, make_event_from_dict
  23. from synapse.federation.federation_base import event_from_pdu_json
  24. from synapse.federation.federation_client import SendJoinResult
  25. from synapse.logging.context import LoggingContext, run_in_background
  26. from synapse.rest import admin
  27. from synapse.rest.client import login, room
  28. from synapse.server import HomeServer
  29. from synapse.util import Clock
  30. from synapse.util.stringutils import random_string
  31. from tests import unittest
  32. from tests.test_utils import event_injection, make_awaitable
  33. logger = logging.getLogger(__name__)
  34. def generate_fake_event_id() -> str:
  35. return "$fake_" + random_string(43)
  36. class FederationTestCase(unittest.FederatingHomeserverTestCase):
  37. servlets = [
  38. admin.register_servlets,
  39. login.register_servlets,
  40. room.register_servlets,
  41. ]
  42. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  43. hs = self.setup_test_homeserver(federation_http_client=None)
  44. self.handler = hs.get_federation_handler()
  45. self.store = hs.get_datastores().main
  46. return hs
  47. def test_exchange_revoked_invite(self) -> None:
  48. user_id = self.register_user("kermit", "test")
  49. tok = self.login("kermit", "test")
  50. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  51. # Send a 3PID invite event with an empty body so it's considered as a revoked one.
  52. invite_token = "sometoken"
  53. self.helper.send_state(
  54. room_id=room_id,
  55. event_type=EventTypes.ThirdPartyInvite,
  56. state_key=invite_token,
  57. body={},
  58. tok=tok,
  59. )
  60. d = self.handler.on_exchange_third_party_invite_request(
  61. event_dict={
  62. "type": EventTypes.Member,
  63. "room_id": room_id,
  64. "sender": user_id,
  65. "state_key": "@someone:example.org",
  66. "content": {
  67. "membership": "invite",
  68. "third_party_invite": {
  69. "display_name": "alice",
  70. "signed": {
  71. "mxid": "@alice:localhost",
  72. "token": invite_token,
  73. "signatures": {
  74. "magic.forest": {
  75. "ed25519:3": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg"
  76. }
  77. },
  78. },
  79. },
  80. },
  81. },
  82. )
  83. failure = self.get_failure(d, AuthError).value
  84. self.assertEqual(failure.code, 403, failure)
  85. self.assertEqual(failure.errcode, Codes.FORBIDDEN, failure)
  86. self.assertEqual(failure.msg, "You are not invited to this room.")
  87. def test_rejected_message_event_state(self) -> None:
  88. """
  89. Check that we store the state group correctly for rejected non-state events.
  90. Regression test for #6289.
  91. """
  92. OTHER_SERVER = "otherserver"
  93. OTHER_USER = "@otheruser:" + OTHER_SERVER
  94. # create the room
  95. user_id = self.register_user("kermit", "test")
  96. tok = self.login("kermit", "test")
  97. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  98. room_version = self.get_success(self.store.get_room_version(room_id))
  99. # pretend that another server has joined
  100. join_event = self._build_and_send_join_event(OTHER_SERVER, OTHER_USER, room_id)
  101. # check the state group
  102. sg = self.get_success(
  103. self.store._get_state_group_for_event(join_event.event_id)
  104. )
  105. # build and send an event which will be rejected
  106. ev = event_from_pdu_json(
  107. {
  108. "type": EventTypes.Message,
  109. "content": {},
  110. "room_id": room_id,
  111. "sender": "@yetanotheruser:" + OTHER_SERVER,
  112. "depth": cast(int, join_event["depth"]) + 1,
  113. "prev_events": [join_event.event_id],
  114. "auth_events": [],
  115. "origin_server_ts": self.clock.time_msec(),
  116. },
  117. room_version,
  118. )
  119. with LoggingContext("send_rejected"):
  120. d = run_in_background(
  121. self.hs.get_federation_event_handler().on_receive_pdu, OTHER_SERVER, ev
  122. )
  123. self.get_success(d)
  124. # that should have been rejected
  125. e = self.get_success(self.store.get_event(ev.event_id, allow_rejected=True))
  126. self.assertIsNotNone(e.rejected_reason)
  127. # ... and the state group should be the same as before
  128. sg2 = self.get_success(self.store._get_state_group_for_event(ev.event_id))
  129. self.assertEqual(sg, sg2)
  130. def test_rejected_state_event_state(self) -> None:
  131. """
  132. Check that we store the state group correctly for rejected state events.
  133. Regression test for #6289.
  134. """
  135. OTHER_SERVER = "otherserver"
  136. OTHER_USER = "@otheruser:" + OTHER_SERVER
  137. # create the room
  138. user_id = self.register_user("kermit", "test")
  139. tok = self.login("kermit", "test")
  140. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  141. room_version = self.get_success(self.store.get_room_version(room_id))
  142. # pretend that another server has joined
  143. join_event = self._build_and_send_join_event(OTHER_SERVER, OTHER_USER, room_id)
  144. # check the state group
  145. sg = self.get_success(
  146. self.store._get_state_group_for_event(join_event.event_id)
  147. )
  148. # build and send an event which will be rejected
  149. ev = event_from_pdu_json(
  150. {
  151. "type": "org.matrix.test",
  152. "state_key": "test_key",
  153. "content": {},
  154. "room_id": room_id,
  155. "sender": "@yetanotheruser:" + OTHER_SERVER,
  156. "depth": cast(int, join_event["depth"]) + 1,
  157. "prev_events": [join_event.event_id],
  158. "auth_events": [],
  159. "origin_server_ts": self.clock.time_msec(),
  160. },
  161. room_version,
  162. )
  163. with LoggingContext("send_rejected"):
  164. d = run_in_background(
  165. self.hs.get_federation_event_handler().on_receive_pdu, OTHER_SERVER, ev
  166. )
  167. self.get_success(d)
  168. # that should have been rejected
  169. e = self.get_success(self.store.get_event(ev.event_id, allow_rejected=True))
  170. self.assertIsNotNone(e.rejected_reason)
  171. # ... and the state group should be the same as before
  172. sg2 = self.get_success(self.store._get_state_group_for_event(ev.event_id))
  173. self.assertEqual(sg, sg2)
  174. def test_backfill_with_many_backward_extremities(self) -> None:
  175. """
  176. Check that we can backfill with many backward extremities.
  177. The goal is to make sure that when we only use a portion
  178. of backwards extremities(the magic number is more than 5),
  179. no errors are thrown.
  180. Regression test, see #11027
  181. """
  182. # create the room
  183. user_id = self.register_user("kermit", "test")
  184. tok = self.login("kermit", "test")
  185. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  186. room_version = self.get_success(self.store.get_room_version(room_id))
  187. # we need a user on the remote server to be a member, so that we can send
  188. # extremity-causing events.
  189. remote_server_user_id = f"@user:{self.OTHER_SERVER_NAME}"
  190. self.get_success(
  191. event_injection.inject_member_event(
  192. self.hs, room_id, remote_server_user_id, "join"
  193. )
  194. )
  195. send_result = self.helper.send(room_id, "first message", tok=tok)
  196. ev1 = self.get_success(
  197. self.store.get_event(send_result["event_id"], allow_none=False)
  198. )
  199. current_state = self.get_success(
  200. self.store.get_events_as_list(
  201. (
  202. self.get_success(self.store.get_partial_current_state_ids(room_id))
  203. ).values()
  204. )
  205. )
  206. # Create "many" backward extremities. The magic number we're trying to
  207. # create more than is 5 which corresponds to the number of backward
  208. # extremities we slice off in `_maybe_backfill_inner`
  209. federation_event_handler = self.hs.get_federation_event_handler()
  210. auth_events = [
  211. ev
  212. for ev in current_state
  213. if (ev.type, ev.state_key)
  214. in {("m.room.create", ""), ("m.room.member", remote_server_user_id)}
  215. ]
  216. for _ in range(0, 8):
  217. event = make_event_from_dict(
  218. self.add_hashes_and_signatures_from_other_server(
  219. {
  220. "origin_server_ts": 1,
  221. "type": "m.room.message",
  222. "content": {
  223. "msgtype": "m.text",
  224. "body": "message connected to fake event",
  225. },
  226. "room_id": room_id,
  227. "sender": remote_server_user_id,
  228. "prev_events": [
  229. ev1.event_id,
  230. # We're creating an backward extremity each time thanks
  231. # to this fake event
  232. generate_fake_event_id(),
  233. ],
  234. "auth_events": [ev.event_id for ev in auth_events],
  235. "depth": ev1.depth + 1,
  236. },
  237. room_version,
  238. ),
  239. room_version,
  240. )
  241. # we poke this directly into _process_received_pdu, to avoid the
  242. # federation handler wanting to backfill the fake event.
  243. state_handler = self.hs.get_state_handler()
  244. context = self.get_success(
  245. state_handler.compute_event_context(
  246. event,
  247. state_ids_before_event={
  248. (e.type, e.state_key): e.event_id for e in current_state
  249. },
  250. partial_state=False,
  251. )
  252. )
  253. self.get_success(
  254. federation_event_handler._process_received_pdu(
  255. self.OTHER_SERVER_NAME,
  256. event,
  257. context,
  258. )
  259. )
  260. # we should now have 8 backwards extremities.
  261. backwards_extremities = self.get_success(
  262. self.store.db_pool.simple_select_list(
  263. "event_backward_extremities",
  264. keyvalues={"room_id": room_id},
  265. retcols=["event_id"],
  266. )
  267. )
  268. self.assertEqual(len(backwards_extremities), 8)
  269. current_depth = 1
  270. limit = 100
  271. with LoggingContext("receive_pdu"):
  272. # Make sure backfill still works
  273. d = run_in_background(
  274. self.hs.get_federation_handler().maybe_backfill,
  275. room_id,
  276. current_depth,
  277. limit,
  278. )
  279. self.get_success(d)
  280. @unittest.override_config(
  281. {"rc_invites": {"per_user": {"per_second": 0.5, "burst_count": 3}}}
  282. )
  283. def test_invite_by_user_ratelimit(self) -> None:
  284. """Tests that invites from federation to a particular user are
  285. actually rate-limited.
  286. """
  287. other_server = "otherserver"
  288. other_user = "@otheruser:" + other_server
  289. # create the room
  290. user_id = self.register_user("kermit", "test")
  291. tok = self.login("kermit", "test")
  292. def create_invite():
  293. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  294. room_version = self.get_success(self.store.get_room_version(room_id))
  295. return event_from_pdu_json(
  296. {
  297. "type": EventTypes.Member,
  298. "content": {"membership": "invite"},
  299. "room_id": room_id,
  300. "sender": other_user,
  301. "state_key": "@user:test",
  302. "depth": 32,
  303. "prev_events": [],
  304. "auth_events": [],
  305. "origin_server_ts": self.clock.time_msec(),
  306. },
  307. room_version,
  308. )
  309. for _ in range(3):
  310. event = create_invite()
  311. self.get_success(
  312. self.handler.on_invite_request(
  313. other_server,
  314. event,
  315. event.room_version,
  316. )
  317. )
  318. event = create_invite()
  319. self.get_failure(
  320. self.handler.on_invite_request(
  321. other_server,
  322. event,
  323. event.room_version,
  324. ),
  325. exc=LimitExceededError,
  326. )
  327. def _build_and_send_join_event(
  328. self, other_server: str, other_user: str, room_id: str
  329. ) -> EventBase:
  330. join_event = self.get_success(
  331. self.handler.on_make_join_request(other_server, room_id, other_user)
  332. )
  333. # the auth code requires that a signature exists, but doesn't check that
  334. # signature... go figure.
  335. join_event.signatures[other_server] = {"x": "y"}
  336. with LoggingContext("send_join"):
  337. d = run_in_background(
  338. self.hs.get_federation_event_handler().on_send_membership_event,
  339. other_server,
  340. join_event,
  341. )
  342. self.get_success(d)
  343. # sanity-check: the room should show that the new user is a member
  344. r = self.get_success(self.store.get_partial_current_state_ids(room_id))
  345. self.assertEqual(r[(EventTypes.Member, other_user)], join_event.event_id)
  346. return join_event
  347. class EventFromPduTestCase(TestCase):
  348. def test_valid_json(self) -> None:
  349. """Valid JSON should be turned into an event."""
  350. ev = event_from_pdu_json(
  351. {
  352. "type": EventTypes.Message,
  353. "content": {"bool": True, "null": None, "int": 1, "str": "foobar"},
  354. "room_id": "!room:test",
  355. "sender": "@user:test",
  356. "depth": 1,
  357. "prev_events": [],
  358. "auth_events": [],
  359. "origin_server_ts": 1234,
  360. },
  361. RoomVersions.V6,
  362. )
  363. self.assertIsInstance(ev, EventBase)
  364. def test_invalid_numbers(self) -> None:
  365. """Invalid values for an integer should be rejected, all floats should be rejected."""
  366. for value in [
  367. -(2**53),
  368. 2**53,
  369. 1.0,
  370. float("inf"),
  371. float("-inf"),
  372. float("nan"),
  373. ]:
  374. with self.assertRaises(SynapseError):
  375. event_from_pdu_json(
  376. {
  377. "type": EventTypes.Message,
  378. "content": {"foo": value},
  379. "room_id": "!room:test",
  380. "sender": "@user:test",
  381. "depth": 1,
  382. "prev_events": [],
  383. "auth_events": [],
  384. "origin_server_ts": 1234,
  385. },
  386. RoomVersions.V6,
  387. )
  388. def test_invalid_nested(self) -> None:
  389. """List and dictionaries are recursively searched."""
  390. with self.assertRaises(SynapseError):
  391. event_from_pdu_json(
  392. {
  393. "type": EventTypes.Message,
  394. "content": {"foo": [{"bar": 2**56}]},
  395. "room_id": "!room:test",
  396. "sender": "@user:test",
  397. "depth": 1,
  398. "prev_events": [],
  399. "auth_events": [],
  400. "origin_server_ts": 1234,
  401. },
  402. RoomVersions.V6,
  403. )
  404. class PartialJoinTestCase(unittest.FederatingHomeserverTestCase):
  405. def test_failed_partial_join_is_clean(self) -> None:
  406. """
  407. Tests that, when failing to partial-join a room, we don't get stuck with
  408. a partial-state flag on a room.
  409. """
  410. fed_handler = self.hs.get_federation_handler()
  411. fed_client = fed_handler.federation_client
  412. room_id = "!room:example.com"
  413. membership_event = make_event_from_dict(
  414. {
  415. "room_id": room_id,
  416. "type": "m.room.member",
  417. "sender": "@alice:test",
  418. "state_key": "@alice:test",
  419. "content": {"membership": "join"},
  420. },
  421. RoomVersions.V10,
  422. )
  423. mock_make_membership_event = Mock(
  424. return_value=make_awaitable(
  425. (
  426. "example.com",
  427. membership_event,
  428. RoomVersions.V10,
  429. )
  430. )
  431. )
  432. EVENT_CREATE = make_event_from_dict(
  433. {
  434. "room_id": room_id,
  435. "type": "m.room.create",
  436. "sender": "@kristina:example.com",
  437. "state_key": "",
  438. "depth": 0,
  439. "content": {"creator": "@kristina:example.com", "room_version": "10"},
  440. "auth_events": [],
  441. "origin_server_ts": 1,
  442. },
  443. room_version=RoomVersions.V10,
  444. )
  445. EVENT_CREATOR_MEMBERSHIP = make_event_from_dict(
  446. {
  447. "room_id": room_id,
  448. "type": "m.room.member",
  449. "sender": "@kristina:example.com",
  450. "state_key": "@kristina:example.com",
  451. "content": {"membership": "join"},
  452. "depth": 1,
  453. "prev_events": [EVENT_CREATE.event_id],
  454. "auth_events": [EVENT_CREATE.event_id],
  455. "origin_server_ts": 1,
  456. },
  457. room_version=RoomVersions.V10,
  458. )
  459. EVENT_INVITATION_MEMBERSHIP = make_event_from_dict(
  460. {
  461. "room_id": room_id,
  462. "type": "m.room.member",
  463. "sender": "@kristina:example.com",
  464. "state_key": "@alice:test",
  465. "content": {"membership": "invite"},
  466. "depth": 2,
  467. "prev_events": [EVENT_CREATOR_MEMBERSHIP.event_id],
  468. "auth_events": [
  469. EVENT_CREATE.event_id,
  470. EVENT_CREATOR_MEMBERSHIP.event_id,
  471. ],
  472. "origin_server_ts": 1,
  473. },
  474. room_version=RoomVersions.V10,
  475. )
  476. mock_send_join = Mock(
  477. return_value=make_awaitable(
  478. SendJoinResult(
  479. membership_event,
  480. "example.com",
  481. state=[
  482. EVENT_CREATE,
  483. EVENT_CREATOR_MEMBERSHIP,
  484. EVENT_INVITATION_MEMBERSHIP,
  485. ],
  486. auth_chain=[
  487. EVENT_CREATE,
  488. EVENT_CREATOR_MEMBERSHIP,
  489. EVENT_INVITATION_MEMBERSHIP,
  490. ],
  491. partial_state=True,
  492. servers_in_room=["example.com"],
  493. )
  494. )
  495. )
  496. with patch.object(
  497. fed_client, "make_membership_event", mock_make_membership_event
  498. ), patch.object(fed_client, "send_join", mock_send_join):
  499. # Join and check that our join event is rejected
  500. # (The join event is rejected because it doesn't have any signatures)
  501. join_exc = self.get_failure(
  502. fed_handler.do_invite_join(["example.com"], room_id, "@alice:test", {}),
  503. SynapseError,
  504. )
  505. self.assertIn("Join event was rejected", str(join_exc))
  506. store = self.hs.get_datastores().main
  507. # Check that we don't have a left-over partial_state entry.
  508. self.assertFalse(
  509. self.get_success(store.is_partial_state_room(room_id)),
  510. f"Stale partial-stated room flag left over for {room_id} after a"
  511. f" failed do_invite_join!",
  512. )