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 List, cast
  16. from unittest import TestCase
  17. from twisted.test.proto_helpers import MemoryReactor
  18. from synapse.api.constants import EventTypes
  19. from synapse.api.errors import AuthError, Codes, LimitExceededError, SynapseError
  20. from synapse.api.room_versions import RoomVersions
  21. from synapse.events import EventBase, make_event_from_dict
  22. from synapse.federation.federation_base import event_from_pdu_json
  23. from synapse.logging.context import LoggingContext, run_in_background
  24. from synapse.rest import admin
  25. from synapse.rest.client import login, room
  26. from synapse.server import HomeServer
  27. from synapse.util import Clock
  28. from synapse.util.stringutils import random_string
  29. from tests import unittest
  30. from tests.test_utils import event_injection
  31. logger = logging.getLogger(__name__)
  32. def generate_fake_event_id() -> str:
  33. return "$fake_" + random_string(43)
  34. class FederationTestCase(unittest.FederatingHomeserverTestCase):
  35. servlets = [
  36. admin.register_servlets,
  37. login.register_servlets,
  38. room.register_servlets,
  39. ]
  40. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  41. hs = self.setup_test_homeserver(federation_http_client=None)
  42. self.handler = hs.get_federation_handler()
  43. self.store = hs.get_datastores().main
  44. self.state_storage = hs.get_storage().state
  45. self._event_auth_handler = hs.get_event_auth_handler()
  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.successResultOf(
  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.successResultOf(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.successResultOf(
  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.successResultOf(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. self.get_success(
  190. event_injection.inject_member_event(
  191. self.hs, room_id, f"@user:{self.OTHER_SERVER_NAME}", "join"
  192. )
  193. )
  194. send_result = self.helper.send(room_id, "first message", tok=tok)
  195. ev1 = self.get_success(
  196. self.store.get_event(send_result["event_id"], allow_none=False)
  197. )
  198. current_state = self.get_success(
  199. self.store.get_events_as_list(
  200. (self.get_success(self.store.get_current_state_ids(room_id))).values()
  201. )
  202. )
  203. # Create "many" backward extremities. The magic number we're trying to
  204. # create more than is 5 which corresponds to the number of backward
  205. # extremities we slice off in `_maybe_backfill_inner`
  206. federation_event_handler = self.hs.get_federation_event_handler()
  207. for _ in range(0, 8):
  208. event = make_event_from_dict(
  209. self.add_hashes_and_signatures(
  210. {
  211. "origin_server_ts": 1,
  212. "type": "m.room.message",
  213. "content": {
  214. "msgtype": "m.text",
  215. "body": "message connected to fake event",
  216. },
  217. "room_id": room_id,
  218. "sender": f"@user:{self.OTHER_SERVER_NAME}",
  219. "prev_events": [
  220. ev1.event_id,
  221. # We're creating an backward extremity each time thanks
  222. # to this fake event
  223. generate_fake_event_id(),
  224. ],
  225. # lazy: *everything* is an auth event
  226. "auth_events": [ev.event_id for ev in current_state],
  227. "depth": ev1.depth + 1,
  228. },
  229. room_version,
  230. ),
  231. room_version,
  232. )
  233. # we poke this directly into _process_received_pdu, to avoid the
  234. # federation handler wanting to backfill the fake event.
  235. self.get_success(
  236. federation_event_handler._process_received_pdu(
  237. self.OTHER_SERVER_NAME,
  238. event,
  239. state_ids={
  240. (e.type, e.state_key): e.event_id for e in current_state
  241. },
  242. )
  243. )
  244. # we should now have 8 backwards extremities.
  245. backwards_extremities = self.get_success(
  246. self.store.db_pool.simple_select_list(
  247. "event_backward_extremities",
  248. keyvalues={"room_id": room_id},
  249. retcols=["event_id"],
  250. )
  251. )
  252. self.assertEqual(len(backwards_extremities), 8)
  253. current_depth = 1
  254. limit = 100
  255. with LoggingContext("receive_pdu"):
  256. # Make sure backfill still works
  257. d = run_in_background(
  258. self.hs.get_federation_handler().maybe_backfill,
  259. room_id,
  260. current_depth,
  261. limit,
  262. )
  263. self.get_success(d)
  264. def test_backfill_floating_outlier_membership_auth(self) -> None:
  265. """
  266. As the local homeserver, check that we can properly process a federated
  267. event from the OTHER_SERVER with auth_events that include a floating
  268. membership event from the OTHER_SERVER.
  269. Regression test, see #10439.
  270. """
  271. OTHER_SERVER = "otherserver"
  272. OTHER_USER = "@otheruser:" + OTHER_SERVER
  273. # create the room
  274. user_id = self.register_user("kermit", "test")
  275. tok = self.login("kermit", "test")
  276. room_id = self.helper.create_room_as(
  277. room_creator=user_id,
  278. is_public=True,
  279. tok=tok,
  280. extra_content={
  281. "preset": "public_chat",
  282. },
  283. )
  284. room_version = self.get_success(self.store.get_room_version(room_id))
  285. prev_event_ids = self.get_success(self.store.get_prev_events_for_room(room_id))
  286. (
  287. most_recent_prev_event_id,
  288. most_recent_prev_event_depth,
  289. ) = self.get_success(self.store.get_max_depth_of(prev_event_ids))
  290. # mapping from (type, state_key) -> state_event_id
  291. assert most_recent_prev_event_id is not None
  292. prev_state_map = self.get_success(
  293. self.state_storage.get_state_ids_for_event(most_recent_prev_event_id)
  294. )
  295. # List of state event ID's
  296. prev_state_ids = list(prev_state_map.values())
  297. auth_event_ids = prev_state_ids
  298. auth_events = list(
  299. self.get_success(self.store.get_events(auth_event_ids)).values()
  300. )
  301. # build a floating outlier member state event
  302. fake_prev_event_id = "$" + random_string(43)
  303. member_event_dict = {
  304. "type": EventTypes.Member,
  305. "content": {
  306. "membership": "join",
  307. },
  308. "state_key": OTHER_USER,
  309. "room_id": room_id,
  310. "sender": OTHER_USER,
  311. "depth": most_recent_prev_event_depth,
  312. "prev_events": [fake_prev_event_id],
  313. "origin_server_ts": self.clock.time_msec(),
  314. "signatures": {OTHER_SERVER: {"ed25519:key_version": "SomeSignatureHere"}},
  315. }
  316. builder = self.hs.get_event_builder_factory().for_room_version(
  317. room_version, member_event_dict
  318. )
  319. member_event = self.get_success(
  320. builder.build(
  321. prev_event_ids=member_event_dict["prev_events"],
  322. auth_event_ids=self._event_auth_handler.compute_auth_events(
  323. builder,
  324. prev_state_map,
  325. for_verification=False,
  326. ),
  327. depth=member_event_dict["depth"],
  328. )
  329. )
  330. # Override the signature added from "test" homeserver that we created the event with
  331. member_event.signatures = member_event_dict["signatures"]
  332. # Add the new member_event to the StateMap
  333. updated_state_map = dict(prev_state_map)
  334. updated_state_map[
  335. (member_event.type, member_event.state_key)
  336. ] = member_event.event_id
  337. auth_events.append(member_event)
  338. # build and send an event authed based on the member event
  339. message_event_dict = {
  340. "type": EventTypes.Message,
  341. "content": {},
  342. "room_id": room_id,
  343. "sender": OTHER_USER,
  344. "depth": most_recent_prev_event_depth,
  345. "prev_events": prev_event_ids.copy(),
  346. "origin_server_ts": self.clock.time_msec(),
  347. "signatures": {OTHER_SERVER: {"ed25519:key_version": "SomeSignatureHere"}},
  348. }
  349. builder = self.hs.get_event_builder_factory().for_room_version(
  350. room_version, message_event_dict
  351. )
  352. message_event = self.get_success(
  353. builder.build(
  354. prev_event_ids=message_event_dict["prev_events"],
  355. auth_event_ids=self._event_auth_handler.compute_auth_events(
  356. builder,
  357. updated_state_map,
  358. for_verification=False,
  359. ),
  360. depth=message_event_dict["depth"],
  361. )
  362. )
  363. # Override the signature added from "test" homeserver that we created the event with
  364. message_event.signatures = message_event_dict["signatures"]
  365. # Stub the /event_auth response from the OTHER_SERVER
  366. async def get_event_auth(
  367. destination: str, room_id: str, event_id: str
  368. ) -> List[EventBase]:
  369. return [
  370. event_from_pdu_json(ae.get_pdu_json(), room_version=room_version)
  371. for ae in auth_events
  372. ]
  373. self.handler.federation_client.get_event_auth = get_event_auth # type: ignore[assignment]
  374. with LoggingContext("receive_pdu"):
  375. # Fake the OTHER_SERVER federating the message event over to our local homeserver
  376. d = run_in_background(
  377. self.hs.get_federation_event_handler().on_receive_pdu,
  378. OTHER_SERVER,
  379. message_event,
  380. )
  381. self.get_success(d)
  382. # Now try and get the events on our local homeserver
  383. stored_event = self.get_success(
  384. self.store.get_event(message_event.event_id, allow_none=True)
  385. )
  386. self.assertTrue(stored_event is not None)
  387. @unittest.override_config(
  388. {"rc_invites": {"per_user": {"per_second": 0.5, "burst_count": 3}}}
  389. )
  390. def test_invite_by_user_ratelimit(self) -> None:
  391. """Tests that invites from federation to a particular user are
  392. actually rate-limited.
  393. """
  394. other_server = "otherserver"
  395. other_user = "@otheruser:" + other_server
  396. # create the room
  397. user_id = self.register_user("kermit", "test")
  398. tok = self.login("kermit", "test")
  399. def create_invite():
  400. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  401. room_version = self.get_success(self.store.get_room_version(room_id))
  402. return event_from_pdu_json(
  403. {
  404. "type": EventTypes.Member,
  405. "content": {"membership": "invite"},
  406. "room_id": room_id,
  407. "sender": other_user,
  408. "state_key": "@user:test",
  409. "depth": 32,
  410. "prev_events": [],
  411. "auth_events": [],
  412. "origin_server_ts": self.clock.time_msec(),
  413. },
  414. room_version,
  415. )
  416. for _ in range(3):
  417. event = create_invite()
  418. self.get_success(
  419. self.handler.on_invite_request(
  420. other_server,
  421. event,
  422. event.room_version,
  423. )
  424. )
  425. event = create_invite()
  426. self.get_failure(
  427. self.handler.on_invite_request(
  428. other_server,
  429. event,
  430. event.room_version,
  431. ),
  432. exc=LimitExceededError,
  433. )
  434. def _build_and_send_join_event(
  435. self, other_server: str, other_user: str, room_id: str
  436. ) -> EventBase:
  437. join_event = self.get_success(
  438. self.handler.on_make_join_request(other_server, room_id, other_user)
  439. )
  440. # the auth code requires that a signature exists, but doesn't check that
  441. # signature... go figure.
  442. join_event.signatures[other_server] = {"x": "y"}
  443. with LoggingContext("send_join"):
  444. d = run_in_background(
  445. self.hs.get_federation_event_handler().on_send_membership_event,
  446. other_server,
  447. join_event,
  448. )
  449. self.get_success(d)
  450. # sanity-check: the room should show that the new user is a member
  451. r = self.get_success(self.store.get_current_state_ids(room_id))
  452. self.assertEqual(r[(EventTypes.Member, other_user)], join_event.event_id)
  453. return join_event
  454. class EventFromPduTestCase(TestCase):
  455. def test_valid_json(self) -> None:
  456. """Valid JSON should be turned into an event."""
  457. ev = event_from_pdu_json(
  458. {
  459. "type": EventTypes.Message,
  460. "content": {"bool": True, "null": None, "int": 1, "str": "foobar"},
  461. "room_id": "!room:test",
  462. "sender": "@user:test",
  463. "depth": 1,
  464. "prev_events": [],
  465. "auth_events": [],
  466. "origin_server_ts": 1234,
  467. },
  468. RoomVersions.V6,
  469. )
  470. self.assertIsInstance(ev, EventBase)
  471. def test_invalid_numbers(self) -> None:
  472. """Invalid values for an integer should be rejected, all floats should be rejected."""
  473. for value in [
  474. -(2**53),
  475. 2**53,
  476. 1.0,
  477. float("inf"),
  478. float("-inf"),
  479. float("nan"),
  480. ]:
  481. with self.assertRaises(SynapseError):
  482. event_from_pdu_json(
  483. {
  484. "type": EventTypes.Message,
  485. "content": {"foo": value},
  486. "room_id": "!room:test",
  487. "sender": "@user:test",
  488. "depth": 1,
  489. "prev_events": [],
  490. "auth_events": [],
  491. "origin_server_ts": 1234,
  492. },
  493. RoomVersions.V6,
  494. )
  495. def test_invalid_nested(self) -> None:
  496. """List and dictionaries are recursively searched."""
  497. with self.assertRaises(SynapseError):
  498. event_from_pdu_json(
  499. {
  500. "type": EventTypes.Message,
  501. "content": {"foo": [{"bar": 2**56}]},
  502. "room_id": "!room:test",
  503. "sender": "@user:test",
  504. "depth": 1,
  505. "prev_events": [],
  506. "auth_events": [],
  507. "origin_server_ts": 1234,
  508. },
  509. RoomVersions.V6,
  510. )