1
0

test_federation.py 22 KB

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