You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1567 line
61 KiB

  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector Ltd
  3. # Copyright 2019-2021 Matrix.org Federation C.I.C
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import random
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Awaitable,
  22. Callable,
  23. Collection,
  24. Dict,
  25. List,
  26. Mapping,
  27. Optional,
  28. Tuple,
  29. Union,
  30. )
  31. from matrix_common.regex import glob_to_regex
  32. from prometheus_client import Counter, Gauge, Histogram
  33. from twisted.internet.abstract import isIPAddress
  34. from twisted.python import failure
  35. from synapse.api.constants import (
  36. Direction,
  37. EduTypes,
  38. EventContentFields,
  39. EventTypes,
  40. Membership,
  41. )
  42. from synapse.api.errors import (
  43. AuthError,
  44. Codes,
  45. FederationError,
  46. IncompatibleRoomVersionError,
  47. NotFoundError,
  48. PartialStateConflictError,
  49. SynapseError,
  50. UnsupportedRoomVersionError,
  51. )
  52. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
  53. from synapse.crypto.event_signing import compute_event_signature
  54. from synapse.events import EventBase
  55. from synapse.events.snapshot import EventContext
  56. from synapse.federation.federation_base import (
  57. FederationBase,
  58. InvalidEventSignatureError,
  59. event_from_pdu_json,
  60. )
  61. from synapse.federation.persistence import TransactionActions
  62. from synapse.federation.units import Edu, Transaction
  63. from synapse.handlers.worker_lock import DELETE_ROOM_LOCK_NAME
  64. from synapse.http.servlet import assert_params_in_dict
  65. from synapse.logging.context import (
  66. make_deferred_yieldable,
  67. nested_logging_context,
  68. run_in_background,
  69. )
  70. from synapse.logging.opentracing import (
  71. SynapseTags,
  72. log_kv,
  73. set_tag,
  74. start_active_span_from_edu,
  75. tag_args,
  76. trace,
  77. )
  78. from synapse.metrics.background_process_metrics import wrap_as_background_process
  79. from synapse.replication.http.federation import (
  80. ReplicationFederationSendEduRestServlet,
  81. ReplicationGetQueryRestServlet,
  82. )
  83. from synapse.storage.databases.main.lock import Lock
  84. from synapse.storage.databases.main.roommember import extract_heroes_from_room_summary
  85. from synapse.storage.roommember import MemberSummary
  86. from synapse.types import JsonDict, StateMap, get_domain_from_id
  87. from synapse.util import unwrapFirstError
  88. from synapse.util.async_helpers import Linearizer, concurrently_execute, gather_results
  89. from synapse.util.caches.response_cache import ResponseCache
  90. from synapse.util.stringutils import parse_server_name
  91. if TYPE_CHECKING:
  92. from synapse.server import HomeServer
  93. # when processing incoming transactions, we try to handle multiple rooms in
  94. # parallel, up to this limit.
  95. TRANSACTION_CONCURRENCY_LIMIT = 10
  96. logger = logging.getLogger(__name__)
  97. received_pdus_counter = Counter("synapse_federation_server_received_pdus", "")
  98. received_edus_counter = Counter("synapse_federation_server_received_edus", "")
  99. received_queries_counter = Counter(
  100. "synapse_federation_server_received_queries", "", ["type"]
  101. )
  102. pdu_process_time = Histogram(
  103. "synapse_federation_server_pdu_process_time",
  104. "Time taken to process an event",
  105. )
  106. last_pdu_ts_metric = Gauge(
  107. "synapse_federation_last_received_pdu_time",
  108. "The timestamp of the last PDU which was successfully received from the given domain",
  109. labelnames=("server_name",),
  110. )
  111. # The name of the lock to use when process events in a room received over
  112. # federation.
  113. _INBOUND_EVENT_HANDLING_LOCK_NAME = "federation_inbound_pdu"
  114. class FederationServer(FederationBase):
  115. def __init__(self, hs: "HomeServer"):
  116. super().__init__(hs)
  117. self.server_name = hs.hostname
  118. self.handler = hs.get_federation_handler()
  119. self._spam_checker_module_callbacks = hs.get_module_api_callbacks().spam_checker
  120. self._federation_event_handler = hs.get_federation_event_handler()
  121. self.state = hs.get_state_handler()
  122. self._event_auth_handler = hs.get_event_auth_handler()
  123. self._room_member_handler = hs.get_room_member_handler()
  124. self._e2e_keys_handler = hs.get_e2e_keys_handler()
  125. self._worker_lock_handler = hs.get_worker_locks_handler()
  126. self._state_storage_controller = hs.get_storage_controllers().state
  127. self.device_handler = hs.get_device_handler()
  128. # Ensure the following handlers are loaded since they register callbacks
  129. # with FederationHandlerRegistry.
  130. hs.get_directory_handler()
  131. self._server_linearizer = Linearizer("fed_server")
  132. # origins that we are currently processing a transaction from.
  133. # a dict from origin to txn id.
  134. self._active_transactions: Dict[str, str] = {}
  135. # We cache results for transaction with the same ID
  136. self._transaction_resp_cache: ResponseCache[Tuple[str, str]] = ResponseCache(
  137. hs.get_clock(), "fed_txn_handler", timeout_ms=30000
  138. )
  139. self.transaction_actions = TransactionActions(self.store)
  140. self.registry = hs.get_federation_registry()
  141. # We cache responses to state queries, as they take a while and often
  142. # come in waves.
  143. self._state_resp_cache: ResponseCache[
  144. Tuple[str, Optional[str]]
  145. ] = ResponseCache(hs.get_clock(), "state_resp", timeout_ms=30000)
  146. self._state_ids_resp_cache: ResponseCache[Tuple[str, str]] = ResponseCache(
  147. hs.get_clock(), "state_ids_resp", timeout_ms=30000
  148. )
  149. self._federation_metrics_domains = (
  150. hs.config.federation.federation_metrics_domains
  151. )
  152. self._room_prejoin_state_types = hs.config.api.room_prejoin_state
  153. # Whether we have started handling old events in the staging area.
  154. self._started_handling_of_staged_events = False
  155. @wrap_as_background_process("_handle_old_staged_events")
  156. async def _handle_old_staged_events(self) -> None:
  157. """Handle old staged events by fetching all rooms that have staged
  158. events and start the processing of each of those rooms.
  159. """
  160. # Get all the rooms IDs with staged events.
  161. room_ids = await self.store.get_all_rooms_with_staged_incoming_events()
  162. # We then shuffle them so that if there are multiple instances doing
  163. # this work they're less likely to collide.
  164. random.shuffle(room_ids)
  165. for room_id in room_ids:
  166. room_version = await self.store.get_room_version(room_id)
  167. # Try and acquire the processing lock for the room, if we get it start a
  168. # background process for handling the events in the room.
  169. lock = await self.store.try_acquire_lock(
  170. _INBOUND_EVENT_HANDLING_LOCK_NAME, room_id
  171. )
  172. if lock:
  173. logger.info("Handling old staged inbound events in %s", room_id)
  174. self._process_incoming_pdus_in_room_inner(
  175. room_id,
  176. room_version,
  177. lock,
  178. )
  179. # We pause a bit so that we don't start handling all rooms at once.
  180. await self._clock.sleep(random.uniform(0, 0.1))
  181. async def on_backfill_request(
  182. self, origin: str, room_id: str, versions: List[str], limit: int
  183. ) -> Tuple[int, Dict[str, Any]]:
  184. async with self._server_linearizer.queue((origin, room_id)):
  185. origin_host, _ = parse_server_name(origin)
  186. await self.check_server_matches_acl(origin_host, room_id)
  187. pdus = await self.handler.on_backfill_request(
  188. origin, room_id, versions, limit
  189. )
  190. res = self._transaction_dict_from_pdus(pdus)
  191. return 200, res
  192. async def on_timestamp_to_event_request(
  193. self, origin: str, room_id: str, timestamp: int, direction: Direction
  194. ) -> Tuple[int, Dict[str, Any]]:
  195. """When we receive a federated `/timestamp_to_event` request,
  196. handle all of the logic for validating and fetching the event.
  197. Args:
  198. origin: The server we received the event from
  199. room_id: Room to fetch the event from
  200. timestamp: The point in time (inclusive) we should navigate from in
  201. the given direction to find the closest event.
  202. direction: indicates whether we should navigate forward
  203. or backward from the given timestamp to find the closest event.
  204. Returns:
  205. Tuple indicating the response status code and dictionary response
  206. body including `event_id`.
  207. """
  208. async with self._server_linearizer.queue((origin, room_id)):
  209. origin_host, _ = parse_server_name(origin)
  210. await self.check_server_matches_acl(origin_host, room_id)
  211. # We only try to fetch data from the local database
  212. event_id = await self.store.get_event_id_for_timestamp(
  213. room_id, timestamp, direction
  214. )
  215. if event_id:
  216. event = await self.store.get_event(
  217. event_id, allow_none=False, allow_rejected=False
  218. )
  219. return 200, {
  220. "event_id": event_id,
  221. "origin_server_ts": event.origin_server_ts,
  222. }
  223. raise SynapseError(
  224. 404,
  225. "Unable to find event from %s in direction %s" % (timestamp, direction),
  226. errcode=Codes.NOT_FOUND,
  227. )
  228. async def on_incoming_transaction(
  229. self,
  230. origin: str,
  231. transaction_id: str,
  232. destination: str,
  233. transaction_data: JsonDict,
  234. ) -> Tuple[int, JsonDict]:
  235. # If we receive a transaction we should make sure that kick off handling
  236. # any old events in the staging area.
  237. if not self._started_handling_of_staged_events:
  238. self._started_handling_of_staged_events = True
  239. self._handle_old_staged_events()
  240. # Start a periodic check for old staged events. This is to handle
  241. # the case where locks time out, e.g. if another process gets killed
  242. # without dropping its locks.
  243. self._clock.looping_call(self._handle_old_staged_events, 60 * 1000)
  244. # keep this as early as possible to make the calculated origin ts as
  245. # accurate as possible.
  246. request_time = self._clock.time_msec()
  247. transaction = Transaction(
  248. transaction_id=transaction_id,
  249. destination=destination,
  250. origin=origin,
  251. origin_server_ts=transaction_data.get("origin_server_ts"), # type: ignore[arg-type]
  252. pdus=transaction_data.get("pdus"),
  253. edus=transaction_data.get("edus"),
  254. )
  255. if not transaction_id:
  256. raise Exception("Transaction missing transaction_id")
  257. logger.debug("[%s] Got transaction", transaction_id)
  258. # Reject malformed transactions early: reject if too many PDUs/EDUs
  259. if len(transaction.pdus) > 50 or len(transaction.edus) > 100:
  260. logger.info("Transaction PDU or EDU count too large. Returning 400")
  261. return 400, {}
  262. # we only process one transaction from each origin at a time. We need to do
  263. # this check here, rather than in _on_incoming_transaction_inner so that we
  264. # don't cache the rejection in _transaction_resp_cache (so that if the txn
  265. # arrives again later, we can process it).
  266. current_transaction = self._active_transactions.get(origin)
  267. if current_transaction and current_transaction != transaction_id:
  268. logger.warning(
  269. "Received another txn %s from %s while still processing %s",
  270. transaction_id,
  271. origin,
  272. current_transaction,
  273. )
  274. return 429, {
  275. "errcode": Codes.UNKNOWN,
  276. "error": "Too many concurrent transactions",
  277. }
  278. # CRITICAL SECTION: we must now not await until we populate _active_transactions
  279. # in _on_incoming_transaction_inner.
  280. # We wrap in a ResponseCache so that we de-duplicate retried
  281. # transactions.
  282. return await self._transaction_resp_cache.wrap(
  283. (origin, transaction_id),
  284. self._on_incoming_transaction_inner,
  285. origin,
  286. transaction,
  287. request_time,
  288. )
  289. async def _on_incoming_transaction_inner(
  290. self, origin: str, transaction: Transaction, request_time: int
  291. ) -> Tuple[int, Dict[str, Any]]:
  292. # CRITICAL SECTION: the first thing we must do (before awaiting) is
  293. # add an entry to _active_transactions.
  294. assert origin not in self._active_transactions
  295. self._active_transactions[origin] = transaction.transaction_id
  296. try:
  297. result = await self._handle_incoming_transaction(
  298. origin, transaction, request_time
  299. )
  300. return result
  301. finally:
  302. del self._active_transactions[origin]
  303. async def _handle_incoming_transaction(
  304. self, origin: str, transaction: Transaction, request_time: int
  305. ) -> Tuple[int, Dict[str, Any]]:
  306. """Process an incoming transaction and return the HTTP response
  307. Args:
  308. origin: the server making the request
  309. transaction: incoming transaction
  310. request_time: timestamp that the HTTP request arrived at
  311. Returns:
  312. HTTP response code and body
  313. """
  314. existing_response = await self.transaction_actions.have_responded(
  315. origin, transaction
  316. )
  317. if existing_response:
  318. logger.debug(
  319. "[%s] We've already responded to this request",
  320. transaction.transaction_id,
  321. )
  322. return existing_response
  323. logger.debug("[%s] Transaction is new", transaction.transaction_id)
  324. # We process PDUs and EDUs in parallel. This is important as we don't
  325. # want to block things like to device messages from reaching clients
  326. # behind the potentially expensive handling of PDUs.
  327. pdu_results, _ = await make_deferred_yieldable(
  328. gather_results(
  329. (
  330. run_in_background(
  331. self._handle_pdus_in_txn, origin, transaction, request_time
  332. ),
  333. run_in_background(self._handle_edus_in_txn, origin, transaction),
  334. ),
  335. consumeErrors=True,
  336. ).addErrback(unwrapFirstError)
  337. )
  338. response = {"pdus": pdu_results}
  339. logger.debug("Returning: %s", str(response))
  340. await self.transaction_actions.set_response(origin, transaction, 200, response)
  341. return 200, response
  342. async def _handle_pdus_in_txn(
  343. self, origin: str, transaction: Transaction, request_time: int
  344. ) -> Dict[str, dict]:
  345. """Process the PDUs in a received transaction.
  346. Args:
  347. origin: the server making the request
  348. transaction: incoming transaction
  349. request_time: timestamp that the HTTP request arrived at
  350. Returns:
  351. A map from event ID of a processed PDU to any errors we should
  352. report back to the sending server.
  353. """
  354. received_pdus_counter.inc(len(transaction.pdus))
  355. origin_host, _ = parse_server_name(origin)
  356. pdus_by_room: Dict[str, List[EventBase]] = {}
  357. newest_pdu_ts = 0
  358. for p in transaction.pdus:
  359. # FIXME (richardv): I don't think this works:
  360. # https://github.com/matrix-org/synapse/issues/8429
  361. if "unsigned" in p:
  362. unsigned = p["unsigned"]
  363. if "age" in unsigned:
  364. p["age"] = unsigned["age"]
  365. if "age" in p:
  366. p["age_ts"] = request_time - int(p["age"])
  367. del p["age"]
  368. # We try and pull out an event ID so that if later checks fail we
  369. # can log something sensible. We don't mandate an event ID here in
  370. # case future event formats get rid of the key.
  371. possible_event_id = p.get("event_id", "<Unknown>")
  372. # Now we get the room ID so that we can check that we know the
  373. # version of the room.
  374. room_id = p.get("room_id")
  375. if not room_id:
  376. logger.info(
  377. "Ignoring PDU as does not have a room_id. Event ID: %s",
  378. possible_event_id,
  379. )
  380. continue
  381. try:
  382. room_version = await self.store.get_room_version(room_id)
  383. except NotFoundError:
  384. logger.info("Ignoring PDU for unknown room_id: %s", room_id)
  385. continue
  386. except UnsupportedRoomVersionError as e:
  387. # this can happen if support for a given room version is withdrawn,
  388. # so that we still get events for said room.
  389. logger.info("Ignoring PDU: %s", e)
  390. continue
  391. event = event_from_pdu_json(p, room_version)
  392. pdus_by_room.setdefault(room_id, []).append(event)
  393. if event.origin_server_ts > newest_pdu_ts:
  394. newest_pdu_ts = event.origin_server_ts
  395. pdu_results = {}
  396. # we can process different rooms in parallel (which is useful if they
  397. # require callouts to other servers to fetch missing events), but
  398. # impose a limit to avoid going too crazy with ram/cpu.
  399. async def process_pdus_for_room(room_id: str) -> None:
  400. with nested_logging_context(room_id):
  401. logger.debug("Processing PDUs for %s", room_id)
  402. try:
  403. await self.check_server_matches_acl(origin_host, room_id)
  404. except AuthError as e:
  405. logger.warning(
  406. "Ignoring PDUs for room %s from banned server", room_id
  407. )
  408. for pdu in pdus_by_room[room_id]:
  409. event_id = pdu.event_id
  410. pdu_results[event_id] = e.error_dict(self.hs.config)
  411. return
  412. for pdu in pdus_by_room[room_id]:
  413. pdu_results[pdu.event_id] = await process_pdu(pdu)
  414. async def process_pdu(pdu: EventBase) -> JsonDict:
  415. """
  416. Processes a pushed PDU sent to us via a `/send` transaction
  417. Returns:
  418. JsonDict representing a "PDU Processing Result" that will be bundled up
  419. with the other processed PDU's in the `/send` transaction and sent back
  420. to remote homeserver.
  421. """
  422. event_id = pdu.event_id
  423. with nested_logging_context(event_id):
  424. try:
  425. await self._handle_received_pdu(origin, pdu)
  426. return {}
  427. except FederationError as e:
  428. logger.warning("Error handling PDU %s: %s", event_id, e)
  429. return {"error": str(e)}
  430. except Exception as e:
  431. f = failure.Failure()
  432. logger.error(
  433. "Failed to handle PDU %s",
  434. event_id,
  435. exc_info=(f.type, f.value, f.getTracebackObject()),
  436. )
  437. return {"error": str(e)}
  438. await concurrently_execute(
  439. process_pdus_for_room, pdus_by_room.keys(), TRANSACTION_CONCURRENCY_LIMIT
  440. )
  441. if newest_pdu_ts and origin in self._federation_metrics_domains:
  442. last_pdu_ts_metric.labels(server_name=origin).set(newest_pdu_ts / 1000)
  443. return pdu_results
  444. async def _handle_edus_in_txn(self, origin: str, transaction: Transaction) -> None:
  445. """Process the EDUs in a received transaction."""
  446. async def _process_edu(edu_dict: JsonDict) -> None:
  447. received_edus_counter.inc()
  448. edu = Edu(
  449. origin=origin,
  450. destination=self.server_name,
  451. edu_type=edu_dict["edu_type"],
  452. content=edu_dict["content"],
  453. )
  454. await self.registry.on_edu(edu.edu_type, origin, edu.content)
  455. await concurrently_execute(
  456. _process_edu,
  457. transaction.edus,
  458. TRANSACTION_CONCURRENCY_LIMIT,
  459. )
  460. async def on_room_state_request(
  461. self, origin: str, room_id: str, event_id: str
  462. ) -> Tuple[int, JsonDict]:
  463. await self._event_auth_handler.assert_host_in_room(room_id, origin)
  464. origin_host, _ = parse_server_name(origin)
  465. await self.check_server_matches_acl(origin_host, room_id)
  466. # we grab the linearizer to protect ourselves from servers which hammer
  467. # us. In theory we might already have the response to this query
  468. # in the cache so we could return it without waiting for the linearizer
  469. # - but that's non-trivial to get right, and anyway somewhat defeats
  470. # the point of the linearizer.
  471. async with self._server_linearizer.queue((origin, room_id)):
  472. resp = await self._state_resp_cache.wrap(
  473. (room_id, event_id),
  474. self._on_context_state_request_compute,
  475. room_id,
  476. event_id,
  477. )
  478. return 200, resp
  479. @trace
  480. @tag_args
  481. async def on_state_ids_request(
  482. self, origin: str, room_id: str, event_id: str
  483. ) -> Tuple[int, JsonDict]:
  484. if not event_id:
  485. raise NotImplementedError("Specify an event")
  486. await self._event_auth_handler.assert_host_in_room(room_id, origin)
  487. origin_host, _ = parse_server_name(origin)
  488. await self.check_server_matches_acl(origin_host, room_id)
  489. resp = await self._state_ids_resp_cache.wrap(
  490. (room_id, event_id),
  491. self._on_state_ids_request_compute,
  492. room_id,
  493. event_id,
  494. )
  495. return 200, resp
  496. @trace
  497. @tag_args
  498. async def _on_state_ids_request_compute(
  499. self, room_id: str, event_id: str
  500. ) -> JsonDict:
  501. state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
  502. auth_chain_ids = await self.store.get_auth_chain_ids(room_id, state_ids)
  503. return {"pdu_ids": state_ids, "auth_chain_ids": list(auth_chain_ids)}
  504. async def _on_context_state_request_compute(
  505. self, room_id: str, event_id: str
  506. ) -> Dict[str, list]:
  507. pdus: Collection[EventBase]
  508. event_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
  509. pdus = await self.store.get_events_as_list(event_ids)
  510. auth_chain = await self.store.get_auth_chain(
  511. room_id, [pdu.event_id for pdu in pdus]
  512. )
  513. return {
  514. "pdus": [pdu.get_pdu_json() for pdu in pdus],
  515. "auth_chain": [pdu.get_pdu_json() for pdu in auth_chain],
  516. }
  517. async def on_pdu_request(
  518. self, origin: str, event_id: str
  519. ) -> Tuple[int, Union[JsonDict, str]]:
  520. pdu = await self.handler.get_persisted_pdu(origin, event_id)
  521. if pdu:
  522. return 200, self._transaction_dict_from_pdus([pdu])
  523. else:
  524. return 404, ""
  525. async def on_query_request(
  526. self, query_type: str, args: Dict[str, str]
  527. ) -> Tuple[int, Dict[str, Any]]:
  528. received_queries_counter.labels(query_type).inc()
  529. resp = await self.registry.on_query(query_type, args)
  530. return 200, resp
  531. async def on_make_join_request(
  532. self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
  533. ) -> Dict[str, Any]:
  534. origin_host, _ = parse_server_name(origin)
  535. await self.check_server_matches_acl(origin_host, room_id)
  536. room_version = await self.store.get_room_version_id(room_id)
  537. if room_version not in supported_versions:
  538. logger.warning(
  539. "Room version %s not in %s", room_version, supported_versions
  540. )
  541. raise IncompatibleRoomVersionError(room_version=room_version)
  542. # Refuse the request if that room has seen too many joins recently.
  543. # This is in addition to the HS-level rate limiting applied by
  544. # BaseFederationServlet.
  545. # type-ignore: mypy doesn't seem able to deduce the type of the limiter(!?)
  546. await self._room_member_handler._join_rate_per_room_limiter.ratelimit( # type: ignore[has-type]
  547. requester=None,
  548. key=room_id,
  549. update=False,
  550. )
  551. pdu = await self.handler.on_make_join_request(origin, room_id, user_id)
  552. return {"event": pdu.get_templated_pdu_json(), "room_version": room_version}
  553. async def on_invite_request(
  554. self, origin: str, content: JsonDict, room_version_id: str
  555. ) -> Dict[str, Any]:
  556. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  557. if not room_version:
  558. raise SynapseError(
  559. 400,
  560. "Homeserver does not support this room version",
  561. Codes.UNSUPPORTED_ROOM_VERSION,
  562. )
  563. pdu = event_from_pdu_json(content, room_version)
  564. origin_host, _ = parse_server_name(origin)
  565. await self.check_server_matches_acl(origin_host, pdu.room_id)
  566. try:
  567. pdu = await self._check_sigs_and_hash(room_version, pdu)
  568. except InvalidEventSignatureError as e:
  569. errmsg = f"event id {pdu.event_id}: {e}"
  570. logger.warning("%s", errmsg)
  571. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  572. ret_pdu = await self.handler.on_invite_request(origin, pdu, room_version)
  573. time_now = self._clock.time_msec()
  574. return {"event": ret_pdu.get_pdu_json(time_now)}
  575. async def on_send_join_request(
  576. self,
  577. origin: str,
  578. content: JsonDict,
  579. room_id: str,
  580. caller_supports_partial_state: bool = False,
  581. ) -> Dict[str, Any]:
  582. set_tag(
  583. SynapseTags.SEND_JOIN_RESPONSE_IS_PARTIAL_STATE,
  584. caller_supports_partial_state,
  585. )
  586. await self._room_member_handler._join_rate_per_room_limiter.ratelimit( # type: ignore[has-type]
  587. requester=None,
  588. key=room_id,
  589. update=False,
  590. )
  591. event, context = await self._on_send_membership_event(
  592. origin, content, Membership.JOIN, room_id
  593. )
  594. prev_state_ids = await context.get_prev_state_ids()
  595. state_event_ids: Collection[str]
  596. servers_in_room: Optional[Collection[str]]
  597. if caller_supports_partial_state:
  598. summary = await self.store.get_room_summary(room_id)
  599. state_event_ids = _get_event_ids_for_partial_state_join(
  600. event, prev_state_ids, summary
  601. )
  602. servers_in_room = await self.state.get_hosts_in_room_at_events(
  603. room_id, event_ids=event.prev_event_ids()
  604. )
  605. else:
  606. state_event_ids = prev_state_ids.values()
  607. servers_in_room = None
  608. auth_chain_event_ids = await self.store.get_auth_chain_ids(
  609. room_id, state_event_ids
  610. )
  611. # if the caller has opted in, we can omit any auth_chain events which are
  612. # already in state_event_ids
  613. if caller_supports_partial_state:
  614. auth_chain_event_ids.difference_update(state_event_ids)
  615. auth_chain_events = await self.store.get_events_as_list(auth_chain_event_ids)
  616. state_events = await self.store.get_events_as_list(state_event_ids)
  617. # we try to do all the async stuff before this point, so that time_now is as
  618. # accurate as possible.
  619. time_now = self._clock.time_msec()
  620. event_json = event.get_pdu_json(time_now)
  621. resp = {
  622. "event": event_json,
  623. "state": [p.get_pdu_json(time_now) for p in state_events],
  624. "auth_chain": [p.get_pdu_json(time_now) for p in auth_chain_events],
  625. "members_omitted": caller_supports_partial_state,
  626. }
  627. if servers_in_room is not None:
  628. resp["servers_in_room"] = list(servers_in_room)
  629. return resp
  630. async def on_make_leave_request(
  631. self, origin: str, room_id: str, user_id: str
  632. ) -> Dict[str, Any]:
  633. origin_host, _ = parse_server_name(origin)
  634. await self.check_server_matches_acl(origin_host, room_id)
  635. pdu = await self.handler.on_make_leave_request(origin, room_id, user_id)
  636. room_version = await self.store.get_room_version_id(room_id)
  637. return {"event": pdu.get_templated_pdu_json(), "room_version": room_version}
  638. async def on_send_leave_request(
  639. self, origin: str, content: JsonDict, room_id: str
  640. ) -> dict:
  641. logger.debug("on_send_leave_request: content: %s", content)
  642. await self._on_send_membership_event(origin, content, Membership.LEAVE, room_id)
  643. return {}
  644. async def on_make_knock_request(
  645. self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
  646. ) -> JsonDict:
  647. """We've received a /make_knock/ request, so we create a partial knock
  648. event for the room and hand that back, along with the room version, to the knocking
  649. homeserver. We do *not* persist or process this event until the other server has
  650. signed it and sent it back.
  651. Args:
  652. origin: The (verified) server name of the requesting server.
  653. room_id: The room to create the knock event in.
  654. user_id: The user to create the knock for.
  655. supported_versions: The room versions supported by the requesting server.
  656. Returns:
  657. The partial knock event.
  658. """
  659. origin_host, _ = parse_server_name(origin)
  660. if await self.store.is_partial_state_room(room_id):
  661. # Before we do anything: check if the room is partial-stated.
  662. # Note that at the time this check was added, `on_make_knock_request` would
  663. # block due to https://github.com/matrix-org/synapse/issues/12997.
  664. raise SynapseError(
  665. 404,
  666. "Unable to handle /make_knock right now; this server is not fully joined.",
  667. errcode=Codes.NOT_FOUND,
  668. )
  669. await self.check_server_matches_acl(origin_host, room_id)
  670. room_version = await self.store.get_room_version(room_id)
  671. # Check that this room version is supported by the remote homeserver
  672. if room_version.identifier not in supported_versions:
  673. logger.warning(
  674. "Room version %s not in %s", room_version.identifier, supported_versions
  675. )
  676. raise IncompatibleRoomVersionError(room_version=room_version.identifier)
  677. # Check that this room supports knocking as defined by its room version
  678. if not room_version.knock_join_rule:
  679. raise SynapseError(
  680. 403,
  681. "This room version does not support knocking",
  682. errcode=Codes.FORBIDDEN,
  683. )
  684. pdu = await self.handler.on_make_knock_request(origin, room_id, user_id)
  685. return {
  686. "event": pdu.get_templated_pdu_json(),
  687. "room_version": room_version.identifier,
  688. }
  689. async def on_send_knock_request(
  690. self,
  691. origin: str,
  692. content: JsonDict,
  693. room_id: str,
  694. ) -> Dict[str, List[JsonDict]]:
  695. """
  696. We have received a knock event for a room. Verify and send the event into the room
  697. on the knocking homeserver's behalf. Then reply with some stripped state from the
  698. room for the knockee.
  699. Args:
  700. origin: The remote homeserver of the knocking user.
  701. content: The content of the request.
  702. room_id: The ID of the room to knock on.
  703. Returns:
  704. The stripped room state.
  705. """
  706. _, context = await self._on_send_membership_event(
  707. origin, content, Membership.KNOCK, room_id
  708. )
  709. # Retrieve stripped state events from the room and send them back to the remote
  710. # server. This will allow the remote server's clients to display information
  711. # related to the room while the knock request is pending.
  712. stripped_room_state = (
  713. await self.store.get_stripped_room_state_from_event_context(
  714. context, self._room_prejoin_state_types
  715. )
  716. )
  717. return {
  718. "knock_room_state": stripped_room_state,
  719. # Since v1.37, Synapse incorrectly used "knock_state_events" for this field.
  720. # Thus, we also populate a 'knock_state_events' with the same content to
  721. # support old instances.
  722. # See https://github.com/matrix-org/synapse/issues/14088.
  723. "knock_state_events": stripped_room_state,
  724. }
  725. async def _on_send_membership_event(
  726. self, origin: str, content: JsonDict, membership_type: str, room_id: str
  727. ) -> Tuple[EventBase, EventContext]:
  728. """Handle an on_send_{join,leave,knock} request
  729. Does some preliminary validation before passing the request on to the
  730. federation handler.
  731. Args:
  732. origin: The (authenticated) requesting server
  733. content: The body of the send_* request - a complete membership event
  734. membership_type: The expected membership type (join or leave, depending
  735. on the endpoint)
  736. room_id: The room_id from the request, to be validated against the room_id
  737. in the event
  738. Returns:
  739. The event and context of the event after inserting it into the room graph.
  740. Raises:
  741. SynapseError if there is a problem with the request, including things like
  742. the room_id not matching or the event not being authorized.
  743. """
  744. assert_params_in_dict(content, ["room_id"])
  745. if content["room_id"] != room_id:
  746. raise SynapseError(
  747. 400,
  748. "Room ID in body does not match that in request path",
  749. Codes.BAD_JSON,
  750. )
  751. # Note that get_room_version throws if the room does not exist here.
  752. room_version = await self.store.get_room_version(room_id)
  753. if await self.store.is_partial_state_room(room_id):
  754. # If our server is still only partially joined, we can't give a complete
  755. # response to /send_join, /send_knock or /send_leave.
  756. # This is because we will not be able to provide the server list (for partial
  757. # joins) or the full state (for full joins).
  758. # Return a 404 as we would if we weren't in the room at all.
  759. logger.info(
  760. f"Rejecting /send_{membership_type} to %s because it's a partial state room",
  761. room_id,
  762. )
  763. raise SynapseError(
  764. 404,
  765. f"Unable to handle /send_{membership_type} right now; this server is not fully joined.",
  766. errcode=Codes.NOT_FOUND,
  767. )
  768. if membership_type == Membership.KNOCK and not room_version.knock_join_rule:
  769. raise SynapseError(
  770. 403,
  771. "This room version does not support knocking",
  772. errcode=Codes.FORBIDDEN,
  773. )
  774. event = event_from_pdu_json(content, room_version)
  775. if event.type != EventTypes.Member or not event.is_state():
  776. raise SynapseError(400, "Not an m.room.member event", Codes.BAD_JSON)
  777. if event.content.get("membership") != membership_type:
  778. raise SynapseError(400, "Not a %s event" % membership_type, Codes.BAD_JSON)
  779. origin_host, _ = parse_server_name(origin)
  780. await self.check_server_matches_acl(origin_host, event.room_id)
  781. logger.debug("_on_send_membership_event: pdu sigs: %s", event.signatures)
  782. # Sign the event since we're vouching on behalf of the remote server that
  783. # the event is valid to be sent into the room. Currently this is only done
  784. # if the user is being joined via restricted join rules.
  785. if (
  786. room_version.restricted_join_rule
  787. and event.membership == Membership.JOIN
  788. and EventContentFields.AUTHORISING_USER in event.content
  789. ):
  790. # We can only authorise our own users.
  791. authorising_server = get_domain_from_id(
  792. event.content[EventContentFields.AUTHORISING_USER]
  793. )
  794. if not self._is_mine_server_name(authorising_server):
  795. raise SynapseError(
  796. 400,
  797. f"Cannot authorise membership event for {authorising_server}. We can only authorise requests from our own homeserver",
  798. )
  799. event.signatures.update(
  800. compute_event_signature(
  801. room_version,
  802. event.get_pdu_json(),
  803. self.hs.hostname,
  804. self.hs.signing_key,
  805. )
  806. )
  807. try:
  808. event = await self._check_sigs_and_hash(room_version, event)
  809. except InvalidEventSignatureError as e:
  810. errmsg = f"event id {event.event_id}: {e}"
  811. logger.warning("%s", errmsg)
  812. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  813. try:
  814. return await self._federation_event_handler.on_send_membership_event(
  815. origin, event
  816. )
  817. except PartialStateConflictError:
  818. # The room was un-partial stated while we were persisting the event.
  819. # Try once more, with full state this time.
  820. logger.info(
  821. "Room %s was un-partial stated during `on_send_membership_event`, trying again.",
  822. room_id,
  823. )
  824. return await self._federation_event_handler.on_send_membership_event(
  825. origin, event
  826. )
  827. async def on_event_auth(
  828. self, origin: str, room_id: str, event_id: str
  829. ) -> Tuple[int, Dict[str, Any]]:
  830. async with self._server_linearizer.queue((origin, room_id)):
  831. await self._event_auth_handler.assert_host_in_room(room_id, origin)
  832. origin_host, _ = parse_server_name(origin)
  833. await self.check_server_matches_acl(origin_host, room_id)
  834. time_now = self._clock.time_msec()
  835. auth_pdus = await self.handler.on_event_auth(event_id)
  836. res = {"auth_chain": [a.get_pdu_json(time_now) for a in auth_pdus]}
  837. return 200, res
  838. async def on_query_client_keys(
  839. self, origin: str, content: Dict[str, str]
  840. ) -> Tuple[int, Dict[str, Any]]:
  841. return await self.on_query_request("client_keys", content)
  842. async def on_query_user_devices(
  843. self, origin: str, user_id: str
  844. ) -> Tuple[int, Dict[str, Any]]:
  845. keys = await self.device_handler.on_federation_query_user_devices(user_id)
  846. return 200, keys
  847. @trace
  848. async def on_claim_client_keys(
  849. self, query: List[Tuple[str, str, str, int]], always_include_fallback_keys: bool
  850. ) -> Dict[str, Any]:
  851. log_kv({"message": "Claiming one time keys.", "user, device pairs": query})
  852. results = await self._e2e_keys_handler.claim_local_one_time_keys(
  853. query, always_include_fallback_keys=always_include_fallback_keys
  854. )
  855. json_result: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
  856. for result in results:
  857. for user_id, device_keys in result.items():
  858. for device_id, keys in device_keys.items():
  859. for key_id, key in keys.items():
  860. json_result.setdefault(user_id, {}).setdefault(device_id, {})[
  861. key_id
  862. ] = key
  863. logger.info(
  864. "Claimed one-time-keys: %s",
  865. ",".join(
  866. (
  867. "%s for %s:%s" % (key_id, user_id, device_id)
  868. for user_id, user_keys in json_result.items()
  869. for device_id, device_keys in user_keys.items()
  870. for key_id, _ in device_keys.items()
  871. )
  872. ),
  873. )
  874. return {"one_time_keys": json_result}
  875. async def on_get_missing_events(
  876. self,
  877. origin: str,
  878. room_id: str,
  879. earliest_events: List[str],
  880. latest_events: List[str],
  881. limit: int,
  882. ) -> Dict[str, list]:
  883. async with self._server_linearizer.queue((origin, room_id)):
  884. origin_host, _ = parse_server_name(origin)
  885. await self.check_server_matches_acl(origin_host, room_id)
  886. logger.debug(
  887. "on_get_missing_events: earliest_events: %r, latest_events: %r,"
  888. " limit: %d",
  889. earliest_events,
  890. latest_events,
  891. limit,
  892. )
  893. missing_events = await self.handler.on_get_missing_events(
  894. origin, room_id, earliest_events, latest_events, limit
  895. )
  896. if len(missing_events) < 5:
  897. logger.debug(
  898. "Returning %d events: %r", len(missing_events), missing_events
  899. )
  900. else:
  901. logger.debug("Returning %d events", len(missing_events))
  902. time_now = self._clock.time_msec()
  903. return {"events": [ev.get_pdu_json(time_now) for ev in missing_events]}
  904. async def on_openid_userinfo(self, token: str) -> Optional[str]:
  905. ts_now_ms = self._clock.time_msec()
  906. return await self.store.get_user_id_for_open_id_token(token, ts_now_ms)
  907. def _transaction_dict_from_pdus(self, pdu_list: List[EventBase]) -> JsonDict:
  908. """Returns a new Transaction containing the given PDUs suitable for
  909. transmission.
  910. """
  911. time_now = self._clock.time_msec()
  912. pdus = [p.get_pdu_json(time_now) for p in pdu_list]
  913. return Transaction(
  914. # Just need a dummy transaction ID and destination since it won't be used.
  915. transaction_id="",
  916. origin=self.server_name,
  917. pdus=pdus,
  918. origin_server_ts=int(time_now),
  919. destination="",
  920. ).get_dict()
  921. async def _handle_received_pdu(self, origin: str, pdu: EventBase) -> None:
  922. """Process a PDU received in a federation /send/ transaction.
  923. If the event is invalid, then this method throws a FederationError.
  924. (The error will then be logged and sent back to the sender (which
  925. probably won't do anything with it), and other events in the
  926. transaction will be processed as normal).
  927. It is likely that we'll then receive other events which refer to
  928. this rejected_event in their prev_events, etc. When that happens,
  929. we'll attempt to fetch the rejected event again, which will presumably
  930. fail, so those second-generation events will also get rejected.
  931. Eventually, we get to the point where there are more than 10 events
  932. between any new events and the original rejected event. Since we
  933. only try to backfill 10 events deep on received pdu, we then accept the
  934. new event, possibly introducing a discontinuity in the DAG, with new
  935. forward extremities, so normal service is approximately returned,
  936. until we try to backfill across the discontinuity.
  937. Args:
  938. origin: server which sent the pdu
  939. pdu: received pdu
  940. Raises: FederationError if the signatures / hash do not match, or
  941. if the event was unacceptable for any other reason (eg, too large,
  942. too many prev_events, couldn't find the prev_events)
  943. """
  944. # We've already checked that we know the room version by this point
  945. room_version = await self.store.get_room_version(pdu.room_id)
  946. # Check signature.
  947. try:
  948. pdu = await self._check_sigs_and_hash(room_version, pdu)
  949. except InvalidEventSignatureError as e:
  950. logger.warning("event id %s: %s", pdu.event_id, e)
  951. raise FederationError("ERROR", 403, str(e), affected=pdu.event_id)
  952. if await self._spam_checker_module_callbacks.should_drop_federated_event(pdu):
  953. logger.warning(
  954. "Unstaged federated event contains spam, dropping %s", pdu.event_id
  955. )
  956. return
  957. # Add the event to our staging area
  958. await self.store.insert_received_event_to_staging(origin, pdu)
  959. # Try and acquire the processing lock for the room, if we get it start a
  960. # background process for handling the events in the room.
  961. lock = await self.store.try_acquire_lock(
  962. _INBOUND_EVENT_HANDLING_LOCK_NAME, pdu.room_id
  963. )
  964. if lock:
  965. self._process_incoming_pdus_in_room_inner(
  966. pdu.room_id, room_version, lock, origin, pdu
  967. )
  968. async def _get_next_nonspam_staged_event_for_room(
  969. self, room_id: str, room_version: RoomVersion
  970. ) -> Optional[Tuple[str, EventBase]]:
  971. """Fetch the first non-spam event from staging queue.
  972. Args:
  973. room_id: the room to fetch the first non-spam event in.
  974. room_version: the version of the room.
  975. Returns:
  976. The first non-spam event in that room.
  977. """
  978. while True:
  979. # We need to do this check outside the lock to avoid a race between
  980. # a new event being inserted by another instance and it attempting
  981. # to acquire the lock.
  982. next = await self.store.get_next_staged_event_for_room(
  983. room_id, room_version
  984. )
  985. if next is None:
  986. return None
  987. origin, event = next
  988. if await self._spam_checker_module_callbacks.should_drop_federated_event(
  989. event
  990. ):
  991. logger.warning(
  992. "Staged federated event contains spam, dropping %s",
  993. event.event_id,
  994. )
  995. continue
  996. return next
  997. @wrap_as_background_process("_process_incoming_pdus_in_room_inner")
  998. async def _process_incoming_pdus_in_room_inner(
  999. self,
  1000. room_id: str,
  1001. room_version: RoomVersion,
  1002. lock: Lock,
  1003. latest_origin: Optional[str] = None,
  1004. latest_event: Optional[EventBase] = None,
  1005. ) -> None:
  1006. """Process events in the staging area for the given room.
  1007. The latest_origin and latest_event args are the latest origin and event
  1008. received (or None to simply pull the next event from the database).
  1009. """
  1010. # The common path is for the event we just received be the only event in
  1011. # the room, so instead of pulling the event out of the DB and parsing
  1012. # the event we just pull out the next event ID and check if that matches.
  1013. if latest_event is not None and latest_origin is not None:
  1014. result = await self.store.get_next_staged_event_id_for_room(room_id)
  1015. if result is None:
  1016. latest_origin = None
  1017. latest_event = None
  1018. else:
  1019. next_origin, next_event_id = result
  1020. if (
  1021. next_origin != latest_origin
  1022. or next_event_id != latest_event.event_id
  1023. ):
  1024. latest_origin = None
  1025. latest_event = None
  1026. if latest_origin is None or latest_event is None:
  1027. next = await self.store.get_next_staged_event_for_room(
  1028. room_id, room_version
  1029. )
  1030. if not next:
  1031. await lock.release()
  1032. return
  1033. origin, event = next
  1034. else:
  1035. origin = latest_origin
  1036. event = latest_event
  1037. # We loop round until there are no more events in the room in the
  1038. # staging area, or we fail to get the lock (which means another process
  1039. # has started processing).
  1040. while True:
  1041. async with lock:
  1042. logger.info("handling received PDU in room %s: %s", room_id, event)
  1043. try:
  1044. with nested_logging_context(event.event_id):
  1045. # We're taking out a lock within a lock, which could
  1046. # lead to deadlocks if we're not careful. However, it is
  1047. # safe on this occasion as we only ever take a write
  1048. # lock when deleting a room, which we would never do
  1049. # while holding the `_INBOUND_EVENT_HANDLING_LOCK_NAME`
  1050. # lock.
  1051. async with self._worker_lock_handler.acquire_read_write_lock(
  1052. DELETE_ROOM_LOCK_NAME, room_id, write=False
  1053. ):
  1054. await self._federation_event_handler.on_receive_pdu(
  1055. origin, event
  1056. )
  1057. except FederationError as e:
  1058. # XXX: Ideally we'd inform the remote we failed to process
  1059. # the event, but we can't return an error in the transaction
  1060. # response (as we've already responded).
  1061. logger.warning("Error handling PDU %s: %s", event.event_id, e)
  1062. except Exception:
  1063. f = failure.Failure()
  1064. logger.error(
  1065. "Failed to handle PDU %s",
  1066. event.event_id,
  1067. exc_info=(f.type, f.value, f.getTracebackObject()),
  1068. )
  1069. received_ts = await self.store.remove_received_event_from_staging(
  1070. origin, event.event_id
  1071. )
  1072. if received_ts is not None:
  1073. pdu_process_time.observe(
  1074. (self._clock.time_msec() - received_ts) / 1000
  1075. )
  1076. next = await self._get_next_nonspam_staged_event_for_room(
  1077. room_id, room_version
  1078. )
  1079. if not next:
  1080. break
  1081. origin, event = next
  1082. # Prune the event queue if it's getting large.
  1083. #
  1084. # We do this *after* handling the first event as the common case is
  1085. # that the queue is empty (/has the single event in), and so there's
  1086. # no need to do this check.
  1087. pruned = await self.store.prune_staged_events_in_room(room_id, room_version)
  1088. if pruned:
  1089. # If we have pruned the queue check we need to refetch the next
  1090. # event to handle.
  1091. next = await self.store.get_next_staged_event_for_room(
  1092. room_id, room_version
  1093. )
  1094. if not next:
  1095. break
  1096. origin, event = next
  1097. new_lock = await self.store.try_acquire_lock(
  1098. _INBOUND_EVENT_HANDLING_LOCK_NAME, room_id
  1099. )
  1100. if not new_lock:
  1101. return
  1102. lock = new_lock
  1103. async def exchange_third_party_invite(
  1104. self, sender_user_id: str, target_user_id: str, room_id: str, signed: Dict
  1105. ) -> None:
  1106. await self.handler.exchange_third_party_invite(
  1107. sender_user_id, target_user_id, room_id, signed
  1108. )
  1109. async def on_exchange_third_party_invite_request(self, event_dict: Dict) -> None:
  1110. await self.handler.on_exchange_third_party_invite_request(event_dict)
  1111. async def check_server_matches_acl(self, server_name: str, room_id: str) -> None:
  1112. """Check if the given server is allowed by the server ACLs in the room
  1113. Args:
  1114. server_name: name of server, *without any port part*
  1115. room_id: ID of the room to check
  1116. Raises:
  1117. AuthError if the server does not match the ACL
  1118. """
  1119. acl_event = await self._storage_controllers.state.get_current_state_event(
  1120. room_id, EventTypes.ServerACL, ""
  1121. )
  1122. if not acl_event or server_matches_acl_event(server_name, acl_event):
  1123. return
  1124. raise AuthError(code=403, msg="Server is banned from room")
  1125. def server_matches_acl_event(server_name: str, acl_event: EventBase) -> bool:
  1126. """Check if the given server is allowed by the ACL event
  1127. Args:
  1128. server_name: name of server, without any port part
  1129. acl_event: m.room.server_acl event
  1130. Returns:
  1131. True if this server is allowed by the ACLs
  1132. """
  1133. logger.debug("Checking %s against acl %s", server_name, acl_event.content)
  1134. # first of all, check if literal IPs are blocked, and if so, whether the
  1135. # server name is a literal IP
  1136. allow_ip_literals = acl_event.content.get("allow_ip_literals", True)
  1137. if not isinstance(allow_ip_literals, bool):
  1138. logger.warning("Ignoring non-bool allow_ip_literals flag")
  1139. allow_ip_literals = True
  1140. if not allow_ip_literals:
  1141. # check for ipv6 literals. These start with '['.
  1142. if server_name[0] == "[":
  1143. return False
  1144. # check for ipv4 literals. We can just lift the routine from twisted.
  1145. if isIPAddress(server_name):
  1146. return False
  1147. # next, check the deny list
  1148. deny = acl_event.content.get("deny", [])
  1149. if not isinstance(deny, (list, tuple)):
  1150. logger.warning("Ignoring non-list deny ACL %s", deny)
  1151. deny = []
  1152. for e in deny:
  1153. if _acl_entry_matches(server_name, e):
  1154. # logger.info("%s matched deny rule %s", server_name, e)
  1155. return False
  1156. # then the allow list.
  1157. allow = acl_event.content.get("allow", [])
  1158. if not isinstance(allow, (list, tuple)):
  1159. logger.warning("Ignoring non-list allow ACL %s", allow)
  1160. allow = []
  1161. for e in allow:
  1162. if _acl_entry_matches(server_name, e):
  1163. # logger.info("%s matched allow rule %s", server_name, e)
  1164. return True
  1165. # everything else should be rejected.
  1166. # logger.info("%s fell through", server_name)
  1167. return False
  1168. def _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:
  1169. if not isinstance(acl_entry, str):
  1170. logger.warning(
  1171. "Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry)
  1172. )
  1173. return False
  1174. regex = glob_to_regex(acl_entry)
  1175. return bool(regex.match(server_name))
  1176. class FederationHandlerRegistry:
  1177. """Allows classes to register themselves as handlers for a given EDU or
  1178. query type for incoming federation traffic.
  1179. """
  1180. def __init__(self, hs: "HomeServer"):
  1181. self.config = hs.config
  1182. self.clock = hs.get_clock()
  1183. self._instance_name = hs.get_instance_name()
  1184. # These are safe to load in monolith mode, but will explode if we try
  1185. # and use them. However we have guards before we use them to ensure that
  1186. # we don't route to ourselves, and in monolith mode that will always be
  1187. # the case.
  1188. self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)
  1189. self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)
  1190. self.edu_handlers: Dict[str, Callable[[str, dict], Awaitable[None]]] = {}
  1191. self.query_handlers: Dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
  1192. # Map from type to instance names that we should route EDU handling to.
  1193. # We randomly choose one instance from the list to route to for each new
  1194. # EDU received.
  1195. self._edu_type_to_instance: Dict[str, List[str]] = {}
  1196. def register_edu_handler(
  1197. self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]
  1198. ) -> None:
  1199. """Sets the handler callable that will be used to handle an incoming
  1200. federation EDU of the given type.
  1201. Args:
  1202. edu_type: The type of the incoming EDU to register handler for
  1203. handler: A callable invoked on incoming EDU
  1204. of the given type. The arguments are the origin server name and
  1205. the EDU contents.
  1206. """
  1207. if edu_type in self.edu_handlers:
  1208. raise KeyError("Already have an EDU handler for %s" % (edu_type,))
  1209. logger.info("Registering federation EDU handler for %r", edu_type)
  1210. self.edu_handlers[edu_type] = handler
  1211. def register_query_handler(
  1212. self, query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
  1213. ) -> None:
  1214. """Sets the handler callable that will be used to handle an incoming
  1215. federation query of the given type.
  1216. Args:
  1217. query_type: Category name of the query, which should match
  1218. the string used by make_query.
  1219. handler: Invoked to handle
  1220. incoming queries of this type. The return will be yielded
  1221. on and the result used as the response to the query request.
  1222. """
  1223. if query_type in self.query_handlers:
  1224. raise KeyError("Already have a Query handler for %s" % (query_type,))
  1225. logger.info("Registering federation query handler for %r", query_type)
  1226. self.query_handlers[query_type] = handler
  1227. def register_instances_for_edu(
  1228. self, edu_type: str, instance_names: List[str]
  1229. ) -> None:
  1230. """Register that the EDU handler is on multiple instances."""
  1231. self._edu_type_to_instance[edu_type] = instance_names
  1232. async def on_edu(self, edu_type: str, origin: str, content: dict) -> None:
  1233. if not self.config.server.use_presence and edu_type == EduTypes.PRESENCE:
  1234. return
  1235. # Check if we have a handler on this instance
  1236. handler = self.edu_handlers.get(edu_type)
  1237. if handler:
  1238. with start_active_span_from_edu(content, "handle_edu"):
  1239. try:
  1240. await handler(origin, content)
  1241. except SynapseError as e:
  1242. logger.info("Failed to handle edu %r: %r", edu_type, e)
  1243. except Exception:
  1244. logger.exception("Failed to handle edu %r", edu_type)
  1245. return
  1246. # Check if we can route it somewhere else that isn't us
  1247. instances = self._edu_type_to_instance.get(edu_type, ["master"])
  1248. if self._instance_name not in instances:
  1249. # Pick an instance randomly so that we don't overload one.
  1250. route_to = random.choice(instances)
  1251. try:
  1252. await self._send_edu(
  1253. instance_name=route_to,
  1254. edu_type=edu_type,
  1255. origin=origin,
  1256. content=content,
  1257. )
  1258. except SynapseError as e:
  1259. logger.info("Failed to handle edu %r: %r", edu_type, e)
  1260. except Exception:
  1261. logger.exception("Failed to handle edu %r", edu_type)
  1262. return
  1263. # Oh well, let's just log and move on.
  1264. logger.warning("No handler registered for EDU type %s", edu_type)
  1265. async def on_query(self, query_type: str, args: dict) -> JsonDict:
  1266. handler = self.query_handlers.get(query_type)
  1267. if handler:
  1268. return await handler(args)
  1269. # Check if we can route it somewhere else that isn't us
  1270. if self._instance_name == "master":
  1271. return await self._get_query_client(query_type=query_type, args=args)
  1272. # Uh oh, no handler! Let's raise an exception so the request returns an
  1273. # error.
  1274. logger.warning("No handler registered for query type %s", query_type)
  1275. raise NotFoundError("No handler for Query type '%s'" % (query_type,))
  1276. def _get_event_ids_for_partial_state_join(
  1277. join_event: EventBase,
  1278. prev_state_ids: StateMap[str],
  1279. summary: Mapping[str, MemberSummary],
  1280. ) -> Collection[str]:
  1281. """Calculate state to be returned in a partial_state send_join
  1282. Args:
  1283. join_event: the join event being send_joined
  1284. prev_state_ids: the event ids of the state before the join
  1285. Returns:
  1286. the event ids to be returned
  1287. """
  1288. # return all non-member events
  1289. state_event_ids = {
  1290. event_id
  1291. for (event_type, state_key), event_id in prev_state_ids.items()
  1292. if event_type != EventTypes.Member
  1293. }
  1294. # we also need the current state of the current user (it's going to
  1295. # be an auth event for the new join, so we may as well return it)
  1296. current_membership_event_id = prev_state_ids.get(
  1297. (EventTypes.Member, join_event.state_key)
  1298. )
  1299. if current_membership_event_id is not None:
  1300. state_event_ids.add(current_membership_event_id)
  1301. name_id = prev_state_ids.get((EventTypes.Name, ""))
  1302. canonical_alias_id = prev_state_ids.get((EventTypes.CanonicalAlias, ""))
  1303. if not name_id and not canonical_alias_id:
  1304. # Also include the hero members of the room (for DM rooms without a title).
  1305. # To do this properly, we should select the correct subset of membership events
  1306. # from `prev_state_ids`. Instead, we are lazier and use the (cached)
  1307. # `get_room_summary` function, which is based on the current state of the room.
  1308. # This introduces races; we choose to ignore them because a) they should be rare
  1309. # and b) even if it's wrong, joining servers will get the full state eventually.
  1310. heroes = extract_heroes_from_room_summary(summary, join_event.state_key)
  1311. for hero in heroes:
  1312. membership_event_id = prev_state_ids.get((EventTypes.Member, hero))
  1313. if membership_event_id:
  1314. state_event_ids.add(membership_event_id)
  1315. return state_event_ids