federation_server.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector Ltd
  3. # Copyright 2019 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. Dict,
  24. Iterable,
  25. List,
  26. Optional,
  27. Tuple,
  28. Union,
  29. )
  30. from prometheus_client import Counter, Gauge, Histogram
  31. from twisted.internet import defer
  32. from twisted.internet.abstract import isIPAddress
  33. from twisted.python import failure
  34. from synapse.api.constants import EduTypes, EventContentFields, EventTypes, Membership
  35. from synapse.api.errors import (
  36. AuthError,
  37. Codes,
  38. FederationError,
  39. IncompatibleRoomVersionError,
  40. NotFoundError,
  41. SynapseError,
  42. UnsupportedRoomVersionError,
  43. )
  44. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
  45. from synapse.crypto.event_signing import compute_event_signature
  46. from synapse.events import EventBase
  47. from synapse.events.snapshot import EventContext
  48. from synapse.federation.federation_base import FederationBase, event_from_pdu_json
  49. from synapse.federation.persistence import TransactionActions
  50. from synapse.federation.units import Edu, Transaction
  51. from synapse.http.servlet import assert_params_in_dict
  52. from synapse.logging.context import (
  53. make_deferred_yieldable,
  54. nested_logging_context,
  55. run_in_background,
  56. )
  57. from synapse.logging.opentracing import log_kv, start_active_span_from_edu, trace
  58. from synapse.logging.utils import log_function
  59. from synapse.metrics.background_process_metrics import wrap_as_background_process
  60. from synapse.replication.http.federation import (
  61. ReplicationFederationSendEduRestServlet,
  62. ReplicationGetQueryRestServlet,
  63. )
  64. from synapse.storage.databases.main.lock import Lock
  65. from synapse.types import JsonDict, get_domain_from_id
  66. from synapse.util import glob_to_regex, json_decoder, unwrapFirstError
  67. from synapse.util.async_helpers import Linearizer, concurrently_execute
  68. from synapse.util.caches.response_cache import ResponseCache
  69. from synapse.util.stringutils import parse_server_name
  70. if TYPE_CHECKING:
  71. from synapse.server import HomeServer
  72. # when processing incoming transactions, we try to handle multiple rooms in
  73. # parallel, up to this limit.
  74. TRANSACTION_CONCURRENCY_LIMIT = 10
  75. logger = logging.getLogger(__name__)
  76. received_pdus_counter = Counter("synapse_federation_server_received_pdus", "")
  77. received_edus_counter = Counter("synapse_federation_server_received_edus", "")
  78. received_queries_counter = Counter(
  79. "synapse_federation_server_received_queries", "", ["type"]
  80. )
  81. pdu_process_time = Histogram(
  82. "synapse_federation_server_pdu_process_time",
  83. "Time taken to process an event",
  84. )
  85. last_pdu_ts_metric = Gauge(
  86. "synapse_federation_last_received_pdu_time",
  87. "The timestamp of the last PDU which was successfully received from the given domain",
  88. labelnames=("server_name",),
  89. )
  90. # The name of the lock to use when process events in a room received over
  91. # federation.
  92. _INBOUND_EVENT_HANDLING_LOCK_NAME = "federation_inbound_pdu"
  93. class FederationServer(FederationBase):
  94. def __init__(self, hs: "HomeServer"):
  95. super().__init__(hs)
  96. self.handler = hs.get_federation_handler()
  97. self._federation_event_handler = hs.get_federation_event_handler()
  98. self.state = hs.get_state_handler()
  99. self._event_auth_handler = hs.get_event_auth_handler()
  100. self.device_handler = hs.get_device_handler()
  101. # Ensure the following handlers are loaded since they register callbacks
  102. # with FederationHandlerRegistry.
  103. hs.get_directory_handler()
  104. self._server_linearizer = Linearizer("fed_server")
  105. # origins that we are currently processing a transaction from.
  106. # a dict from origin to txn id.
  107. self._active_transactions: Dict[str, str] = {}
  108. # We cache results for transaction with the same ID
  109. self._transaction_resp_cache: ResponseCache[Tuple[str, str]] = ResponseCache(
  110. hs.get_clock(), "fed_txn_handler", timeout_ms=30000
  111. )
  112. self.transaction_actions = TransactionActions(self.store)
  113. self.registry = hs.get_federation_registry()
  114. # We cache responses to state queries, as they take a while and often
  115. # come in waves.
  116. self._state_resp_cache: ResponseCache[
  117. Tuple[str, Optional[str]]
  118. ] = ResponseCache(hs.get_clock(), "state_resp", timeout_ms=30000)
  119. self._state_ids_resp_cache: ResponseCache[Tuple[str, str]] = ResponseCache(
  120. hs.get_clock(), "state_ids_resp", timeout_ms=30000
  121. )
  122. self._federation_metrics_domains = (
  123. hs.config.federation.federation_metrics_domains
  124. )
  125. self._room_prejoin_state_types = hs.config.api.room_prejoin_state
  126. # Whether we have started handling old events in the staging area.
  127. self._started_handling_of_staged_events = False
  128. @wrap_as_background_process("_handle_old_staged_events")
  129. async def _handle_old_staged_events(self) -> None:
  130. """Handle old staged events by fetching all rooms that have staged
  131. events and start the processing of each of those rooms.
  132. """
  133. # Get all the rooms IDs with staged events.
  134. room_ids = await self.store.get_all_rooms_with_staged_incoming_events()
  135. # We then shuffle them so that if there are multiple instances doing
  136. # this work they're less likely to collide.
  137. random.shuffle(room_ids)
  138. for room_id in room_ids:
  139. room_version = await self.store.get_room_version(room_id)
  140. # Try and acquire the processing lock for the room, if we get it start a
  141. # background process for handling the events in the room.
  142. lock = await self.store.try_acquire_lock(
  143. _INBOUND_EVENT_HANDLING_LOCK_NAME, room_id
  144. )
  145. if lock:
  146. logger.info("Handling old staged inbound events in %s", room_id)
  147. self._process_incoming_pdus_in_room_inner(
  148. room_id,
  149. room_version,
  150. lock,
  151. )
  152. # We pause a bit so that we don't start handling all rooms at once.
  153. await self._clock.sleep(random.uniform(0, 0.1))
  154. async def on_backfill_request(
  155. self, origin: str, room_id: str, versions: List[str], limit: int
  156. ) -> Tuple[int, Dict[str, Any]]:
  157. with (await self._server_linearizer.queue((origin, room_id))):
  158. origin_host, _ = parse_server_name(origin)
  159. await self.check_server_matches_acl(origin_host, room_id)
  160. pdus = await self.handler.on_backfill_request(
  161. origin, room_id, versions, limit
  162. )
  163. res = self._transaction_dict_from_pdus(pdus)
  164. return 200, res
  165. async def on_incoming_transaction(
  166. self,
  167. origin: str,
  168. transaction_id: str,
  169. destination: str,
  170. transaction_data: JsonDict,
  171. ) -> Tuple[int, JsonDict]:
  172. # If we receive a transaction we should make sure that kick off handling
  173. # any old events in the staging area.
  174. if not self._started_handling_of_staged_events:
  175. self._started_handling_of_staged_events = True
  176. self._handle_old_staged_events()
  177. # keep this as early as possible to make the calculated origin ts as
  178. # accurate as possible.
  179. request_time = self._clock.time_msec()
  180. transaction = Transaction(
  181. transaction_id=transaction_id,
  182. destination=destination,
  183. origin=origin,
  184. origin_server_ts=transaction_data.get("origin_server_ts"), # type: ignore
  185. pdus=transaction_data.get("pdus"), # type: ignore
  186. edus=transaction_data.get("edus"),
  187. )
  188. if not transaction_id:
  189. raise Exception("Transaction missing transaction_id")
  190. logger.debug("[%s] Got transaction", transaction_id)
  191. # Reject malformed transactions early: reject if too many PDUs/EDUs
  192. if len(transaction.pdus) > 50 or len(transaction.edus) > 100:
  193. logger.info("Transaction PDU or EDU count too large. Returning 400")
  194. return 400, {}
  195. # we only process one transaction from each origin at a time. We need to do
  196. # this check here, rather than in _on_incoming_transaction_inner so that we
  197. # don't cache the rejection in _transaction_resp_cache (so that if the txn
  198. # arrives again later, we can process it).
  199. current_transaction = self._active_transactions.get(origin)
  200. if current_transaction and current_transaction != transaction_id:
  201. logger.warning(
  202. "Received another txn %s from %s while still processing %s",
  203. transaction_id,
  204. origin,
  205. current_transaction,
  206. )
  207. return 429, {
  208. "errcode": Codes.UNKNOWN,
  209. "error": "Too many concurrent transactions",
  210. }
  211. # CRITICAL SECTION: we must now not await until we populate _active_transactions
  212. # in _on_incoming_transaction_inner.
  213. # We wrap in a ResponseCache so that we de-duplicate retried
  214. # transactions.
  215. return await self._transaction_resp_cache.wrap(
  216. (origin, transaction_id),
  217. self._on_incoming_transaction_inner,
  218. origin,
  219. transaction,
  220. request_time,
  221. )
  222. async def _on_incoming_transaction_inner(
  223. self, origin: str, transaction: Transaction, request_time: int
  224. ) -> Tuple[int, Dict[str, Any]]:
  225. # CRITICAL SECTION: the first thing we must do (before awaiting) is
  226. # add an entry to _active_transactions.
  227. assert origin not in self._active_transactions
  228. self._active_transactions[origin] = transaction.transaction_id
  229. try:
  230. result = await self._handle_incoming_transaction(
  231. origin, transaction, request_time
  232. )
  233. return result
  234. finally:
  235. del self._active_transactions[origin]
  236. async def _handle_incoming_transaction(
  237. self, origin: str, transaction: Transaction, request_time: int
  238. ) -> Tuple[int, Dict[str, Any]]:
  239. """Process an incoming transaction and return the HTTP response
  240. Args:
  241. origin: the server making the request
  242. transaction: incoming transaction
  243. request_time: timestamp that the HTTP request arrived at
  244. Returns:
  245. HTTP response code and body
  246. """
  247. existing_response = await self.transaction_actions.have_responded(
  248. origin, transaction
  249. )
  250. if existing_response:
  251. logger.debug(
  252. "[%s] We've already responded to this request",
  253. transaction.transaction_id,
  254. )
  255. return existing_response
  256. logger.debug("[%s] Transaction is new", transaction.transaction_id)
  257. # We process PDUs and EDUs in parallel. This is important as we don't
  258. # want to block things like to device messages from reaching clients
  259. # behind the potentially expensive handling of PDUs.
  260. pdu_results, _ = await make_deferred_yieldable(
  261. defer.gatherResults(
  262. [
  263. run_in_background(
  264. self._handle_pdus_in_txn, origin, transaction, request_time
  265. ),
  266. run_in_background(self._handle_edus_in_txn, origin, transaction),
  267. ],
  268. consumeErrors=True,
  269. ).addErrback(unwrapFirstError)
  270. )
  271. response = {"pdus": pdu_results}
  272. logger.debug("Returning: %s", str(response))
  273. await self.transaction_actions.set_response(origin, transaction, 200, response)
  274. return 200, response
  275. async def _handle_pdus_in_txn(
  276. self, origin: str, transaction: Transaction, request_time: int
  277. ) -> Dict[str, dict]:
  278. """Process the PDUs in a received transaction.
  279. Args:
  280. origin: the server making the request
  281. transaction: incoming transaction
  282. request_time: timestamp that the HTTP request arrived at
  283. Returns:
  284. A map from event ID of a processed PDU to any errors we should
  285. report back to the sending server.
  286. """
  287. received_pdus_counter.inc(len(transaction.pdus))
  288. origin_host, _ = parse_server_name(origin)
  289. pdus_by_room: Dict[str, List[EventBase]] = {}
  290. newest_pdu_ts = 0
  291. for p in transaction.pdus:
  292. # FIXME (richardv): I don't think this works:
  293. # https://github.com/matrix-org/synapse/issues/8429
  294. if "unsigned" in p:
  295. unsigned = p["unsigned"]
  296. if "age" in unsigned:
  297. p["age"] = unsigned["age"]
  298. if "age" in p:
  299. p["age_ts"] = request_time - int(p["age"])
  300. del p["age"]
  301. # We try and pull out an event ID so that if later checks fail we
  302. # can log something sensible. We don't mandate an event ID here in
  303. # case future event formats get rid of the key.
  304. possible_event_id = p.get("event_id", "<Unknown>")
  305. # Now we get the room ID so that we can check that we know the
  306. # version of the room.
  307. room_id = p.get("room_id")
  308. if not room_id:
  309. logger.info(
  310. "Ignoring PDU as does not have a room_id. Event ID: %s",
  311. possible_event_id,
  312. )
  313. continue
  314. try:
  315. room_version = await self.store.get_room_version(room_id)
  316. except NotFoundError:
  317. logger.info("Ignoring PDU for unknown room_id: %s", room_id)
  318. continue
  319. except UnsupportedRoomVersionError as e:
  320. # this can happen if support for a given room version is withdrawn,
  321. # so that we still get events for said room.
  322. logger.info("Ignoring PDU: %s", e)
  323. continue
  324. event = event_from_pdu_json(p, room_version)
  325. pdus_by_room.setdefault(room_id, []).append(event)
  326. if event.origin_server_ts > newest_pdu_ts:
  327. newest_pdu_ts = event.origin_server_ts
  328. pdu_results = {}
  329. # we can process different rooms in parallel (which is useful if they
  330. # require callouts to other servers to fetch missing events), but
  331. # impose a limit to avoid going too crazy with ram/cpu.
  332. async def process_pdus_for_room(room_id: str):
  333. with nested_logging_context(room_id):
  334. logger.debug("Processing PDUs for %s", room_id)
  335. try:
  336. await self.check_server_matches_acl(origin_host, room_id)
  337. except AuthError as e:
  338. logger.warning(
  339. "Ignoring PDUs for room %s from banned server", room_id
  340. )
  341. for pdu in pdus_by_room[room_id]:
  342. event_id = pdu.event_id
  343. pdu_results[event_id] = e.error_dict()
  344. return
  345. for pdu in pdus_by_room[room_id]:
  346. pdu_results[pdu.event_id] = await process_pdu(pdu)
  347. async def process_pdu(pdu: EventBase) -> JsonDict:
  348. event_id = pdu.event_id
  349. with nested_logging_context(event_id):
  350. try:
  351. await self._handle_received_pdu(origin, pdu)
  352. return {}
  353. except FederationError as e:
  354. logger.warning("Error handling PDU %s: %s", event_id, e)
  355. return {"error": str(e)}
  356. except Exception as e:
  357. f = failure.Failure()
  358. logger.error(
  359. "Failed to handle PDU %s",
  360. event_id,
  361. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
  362. )
  363. return {"error": str(e)}
  364. await concurrently_execute(
  365. process_pdus_for_room, pdus_by_room.keys(), TRANSACTION_CONCURRENCY_LIMIT
  366. )
  367. if newest_pdu_ts and origin in self._federation_metrics_domains:
  368. last_pdu_ts_metric.labels(server_name=origin).set(newest_pdu_ts / 1000)
  369. return pdu_results
  370. async def _handle_edus_in_txn(self, origin: str, transaction: Transaction) -> None:
  371. """Process the EDUs in a received transaction."""
  372. async def _process_edu(edu_dict: JsonDict) -> None:
  373. received_edus_counter.inc()
  374. edu = Edu(
  375. origin=origin,
  376. destination=self.server_name,
  377. edu_type=edu_dict["edu_type"],
  378. content=edu_dict["content"],
  379. )
  380. await self.registry.on_edu(edu.edu_type, origin, edu.content)
  381. await concurrently_execute(
  382. _process_edu,
  383. transaction.edus,
  384. TRANSACTION_CONCURRENCY_LIMIT,
  385. )
  386. async def on_room_state_request(
  387. self, origin: str, room_id: str, event_id: Optional[str]
  388. ) -> Tuple[int, JsonDict]:
  389. origin_host, _ = parse_server_name(origin)
  390. await self.check_server_matches_acl(origin_host, room_id)
  391. in_room = await self._event_auth_handler.check_host_in_room(room_id, origin)
  392. if not in_room:
  393. raise AuthError(403, "Host not in room.")
  394. # we grab the linearizer to protect ourselves from servers which hammer
  395. # us. In theory we might already have the response to this query
  396. # in the cache so we could return it without waiting for the linearizer
  397. # - but that's non-trivial to get right, and anyway somewhat defeats
  398. # the point of the linearizer.
  399. with (await self._server_linearizer.queue((origin, room_id))):
  400. resp: JsonDict = dict(
  401. await self._state_resp_cache.wrap(
  402. (room_id, event_id),
  403. self._on_context_state_request_compute,
  404. room_id,
  405. event_id,
  406. )
  407. )
  408. room_version = await self.store.get_room_version_id(room_id)
  409. resp["room_version"] = room_version
  410. return 200, resp
  411. async def on_state_ids_request(
  412. self, origin: str, room_id: str, event_id: str
  413. ) -> Tuple[int, Dict[str, Any]]:
  414. if not event_id:
  415. raise NotImplementedError("Specify an event")
  416. origin_host, _ = parse_server_name(origin)
  417. await self.check_server_matches_acl(origin_host, room_id)
  418. in_room = await self._event_auth_handler.check_host_in_room(room_id, origin)
  419. if not in_room:
  420. raise AuthError(403, "Host not in room.")
  421. resp = await self._state_ids_resp_cache.wrap(
  422. (room_id, event_id),
  423. self._on_state_ids_request_compute,
  424. room_id,
  425. event_id,
  426. )
  427. return 200, resp
  428. async def _on_state_ids_request_compute(self, room_id, event_id):
  429. state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
  430. auth_chain_ids = await self.store.get_auth_chain_ids(room_id, state_ids)
  431. return {"pdu_ids": state_ids, "auth_chain_ids": auth_chain_ids}
  432. async def _on_context_state_request_compute(
  433. self, room_id: str, event_id: Optional[str]
  434. ) -> Dict[str, list]:
  435. if event_id:
  436. pdus: Iterable[EventBase] = await self.handler.get_state_for_pdu(
  437. room_id, event_id
  438. )
  439. else:
  440. pdus = (await self.state.get_current_state(room_id)).values()
  441. auth_chain = await self.store.get_auth_chain(
  442. room_id, [pdu.event_id for pdu in pdus]
  443. )
  444. return {
  445. "pdus": [pdu.get_pdu_json() for pdu in pdus],
  446. "auth_chain": [pdu.get_pdu_json() for pdu in auth_chain],
  447. }
  448. async def on_pdu_request(
  449. self, origin: str, event_id: str
  450. ) -> Tuple[int, Union[JsonDict, str]]:
  451. pdu = await self.handler.get_persisted_pdu(origin, event_id)
  452. if pdu:
  453. return 200, self._transaction_dict_from_pdus([pdu])
  454. else:
  455. return 404, ""
  456. async def on_query_request(
  457. self, query_type: str, args: Dict[str, str]
  458. ) -> Tuple[int, Dict[str, Any]]:
  459. received_queries_counter.labels(query_type).inc()
  460. resp = await self.registry.on_query(query_type, args)
  461. return 200, resp
  462. async def on_make_join_request(
  463. self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
  464. ) -> Dict[str, Any]:
  465. origin_host, _ = parse_server_name(origin)
  466. await self.check_server_matches_acl(origin_host, room_id)
  467. room_version = await self.store.get_room_version_id(room_id)
  468. if room_version not in supported_versions:
  469. logger.warning(
  470. "Room version %s not in %s", room_version, supported_versions
  471. )
  472. raise IncompatibleRoomVersionError(room_version=room_version)
  473. pdu = await self.handler.on_make_join_request(origin, room_id, user_id)
  474. return {"event": pdu.get_templated_pdu_json(), "room_version": room_version}
  475. async def on_invite_request(
  476. self, origin: str, content: JsonDict, room_version_id: str
  477. ) -> Dict[str, Any]:
  478. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  479. if not room_version:
  480. raise SynapseError(
  481. 400,
  482. "Homeserver does not support this room version",
  483. Codes.UNSUPPORTED_ROOM_VERSION,
  484. )
  485. pdu = event_from_pdu_json(content, room_version)
  486. origin_host, _ = parse_server_name(origin)
  487. await self.check_server_matches_acl(origin_host, pdu.room_id)
  488. pdu = await self._check_sigs_and_hash(room_version, pdu)
  489. ret_pdu = await self.handler.on_invite_request(origin, pdu, room_version)
  490. time_now = self._clock.time_msec()
  491. return {"event": ret_pdu.get_pdu_json(time_now)}
  492. async def on_send_join_request(
  493. self, origin: str, content: JsonDict, room_id: str
  494. ) -> Dict[str, Any]:
  495. event, context = await self._on_send_membership_event(
  496. origin, content, Membership.JOIN, room_id
  497. )
  498. prev_state_ids = await context.get_prev_state_ids()
  499. state_ids = list(prev_state_ids.values())
  500. auth_chain = await self.store.get_auth_chain(room_id, state_ids)
  501. state = await self.store.get_events(state_ids)
  502. time_now = self._clock.time_msec()
  503. return {
  504. "org.matrix.msc3083.v2.event": event.get_pdu_json(),
  505. "state": [p.get_pdu_json(time_now) for p in state.values()],
  506. "auth_chain": [p.get_pdu_json(time_now) for p in auth_chain],
  507. }
  508. async def on_make_leave_request(
  509. self, origin: str, room_id: str, user_id: str
  510. ) -> Dict[str, Any]:
  511. origin_host, _ = parse_server_name(origin)
  512. await self.check_server_matches_acl(origin_host, room_id)
  513. pdu = await self.handler.on_make_leave_request(origin, room_id, user_id)
  514. room_version = await self.store.get_room_version_id(room_id)
  515. return {"event": pdu.get_templated_pdu_json(), "room_version": room_version}
  516. async def on_send_leave_request(
  517. self, origin: str, content: JsonDict, room_id: str
  518. ) -> dict:
  519. logger.debug("on_send_leave_request: content: %s", content)
  520. await self._on_send_membership_event(origin, content, Membership.LEAVE, room_id)
  521. return {}
  522. async def on_make_knock_request(
  523. self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
  524. ) -> JsonDict:
  525. """We've received a /make_knock/ request, so we create a partial knock
  526. event for the room and hand that back, along with the room version, to the knocking
  527. homeserver. We do *not* persist or process this event until the other server has
  528. signed it and sent it back.
  529. Args:
  530. origin: The (verified) server name of the requesting server.
  531. room_id: The room to create the knock event in.
  532. user_id: The user to create the knock for.
  533. supported_versions: The room versions supported by the requesting server.
  534. Returns:
  535. The partial knock event.
  536. """
  537. origin_host, _ = parse_server_name(origin)
  538. await self.check_server_matches_acl(origin_host, room_id)
  539. room_version = await self.store.get_room_version(room_id)
  540. # Check that this room version is supported by the remote homeserver
  541. if room_version.identifier not in supported_versions:
  542. logger.warning(
  543. "Room version %s not in %s", room_version.identifier, supported_versions
  544. )
  545. raise IncompatibleRoomVersionError(room_version=room_version.identifier)
  546. # Check that this room supports knocking as defined by its room version
  547. if not room_version.msc2403_knocking:
  548. raise SynapseError(
  549. 403,
  550. "This room version does not support knocking",
  551. errcode=Codes.FORBIDDEN,
  552. )
  553. pdu = await self.handler.on_make_knock_request(origin, room_id, user_id)
  554. return {
  555. "event": pdu.get_templated_pdu_json(),
  556. "room_version": room_version.identifier,
  557. }
  558. async def on_send_knock_request(
  559. self,
  560. origin: str,
  561. content: JsonDict,
  562. room_id: str,
  563. ) -> Dict[str, List[JsonDict]]:
  564. """
  565. We have received a knock event for a room. Verify and send the event into the room
  566. on the knocking homeserver's behalf. Then reply with some stripped state from the
  567. room for the knockee.
  568. Args:
  569. origin: The remote homeserver of the knocking user.
  570. content: The content of the request.
  571. room_id: The ID of the room to knock on.
  572. Returns:
  573. The stripped room state.
  574. """
  575. _, context = await self._on_send_membership_event(
  576. origin, content, Membership.KNOCK, room_id
  577. )
  578. # Retrieve stripped state events from the room and send them back to the remote
  579. # server. This will allow the remote server's clients to display information
  580. # related to the room while the knock request is pending.
  581. stripped_room_state = (
  582. await self.store.get_stripped_room_state_from_event_context(
  583. context, self._room_prejoin_state_types
  584. )
  585. )
  586. return {"knock_state_events": stripped_room_state}
  587. async def _on_send_membership_event(
  588. self, origin: str, content: JsonDict, membership_type: str, room_id: str
  589. ) -> Tuple[EventBase, EventContext]:
  590. """Handle an on_send_{join,leave,knock} request
  591. Does some preliminary validation before passing the request on to the
  592. federation handler.
  593. Args:
  594. origin: The (authenticated) requesting server
  595. content: The body of the send_* request - a complete membership event
  596. membership_type: The expected membership type (join or leave, depending
  597. on the endpoint)
  598. room_id: The room_id from the request, to be validated against the room_id
  599. in the event
  600. Returns:
  601. The event and context of the event after inserting it into the room graph.
  602. Raises:
  603. SynapseError if there is a problem with the request, including things like
  604. the room_id not matching or the event not being authorized.
  605. """
  606. assert_params_in_dict(content, ["room_id"])
  607. if content["room_id"] != room_id:
  608. raise SynapseError(
  609. 400,
  610. "Room ID in body does not match that in request path",
  611. Codes.BAD_JSON,
  612. )
  613. room_version = await self.store.get_room_version(room_id)
  614. if membership_type == Membership.KNOCK and not room_version.msc2403_knocking:
  615. raise SynapseError(
  616. 403,
  617. "This room version does not support knocking",
  618. errcode=Codes.FORBIDDEN,
  619. )
  620. event = event_from_pdu_json(content, room_version)
  621. if event.type != EventTypes.Member or not event.is_state():
  622. raise SynapseError(400, "Not an m.room.member event", Codes.BAD_JSON)
  623. if event.content.get("membership") != membership_type:
  624. raise SynapseError(400, "Not a %s event" % membership_type, Codes.BAD_JSON)
  625. origin_host, _ = parse_server_name(origin)
  626. await self.check_server_matches_acl(origin_host, event.room_id)
  627. logger.debug("_on_send_membership_event: pdu sigs: %s", event.signatures)
  628. # Sign the event since we're vouching on behalf of the remote server that
  629. # the event is valid to be sent into the room. Currently this is only done
  630. # if the user is being joined via restricted join rules.
  631. if (
  632. room_version.msc3083_join_rules
  633. and event.membership == Membership.JOIN
  634. and EventContentFields.AUTHORISING_USER in event.content
  635. ):
  636. # We can only authorise our own users.
  637. authorising_server = get_domain_from_id(
  638. event.content[EventContentFields.AUTHORISING_USER]
  639. )
  640. if authorising_server != self.server_name:
  641. raise SynapseError(
  642. 400,
  643. f"Cannot authorise request from resident server: {authorising_server}",
  644. )
  645. event.signatures.update(
  646. compute_event_signature(
  647. room_version,
  648. event.get_pdu_json(),
  649. self.hs.hostname,
  650. self.hs.signing_key,
  651. )
  652. )
  653. event = await self._check_sigs_and_hash(room_version, event)
  654. return await self._federation_event_handler.on_send_membership_event(
  655. origin, event
  656. )
  657. async def on_event_auth(
  658. self, origin: str, room_id: str, event_id: str
  659. ) -> Tuple[int, Dict[str, Any]]:
  660. with (await self._server_linearizer.queue((origin, room_id))):
  661. origin_host, _ = parse_server_name(origin)
  662. await self.check_server_matches_acl(origin_host, room_id)
  663. time_now = self._clock.time_msec()
  664. auth_pdus = await self.handler.on_event_auth(event_id)
  665. res = {"auth_chain": [a.get_pdu_json(time_now) for a in auth_pdus]}
  666. return 200, res
  667. @log_function
  668. async def on_query_client_keys(
  669. self, origin: str, content: Dict[str, str]
  670. ) -> Tuple[int, Dict[str, Any]]:
  671. return await self.on_query_request("client_keys", content)
  672. async def on_query_user_devices(
  673. self, origin: str, user_id: str
  674. ) -> Tuple[int, Dict[str, Any]]:
  675. keys = await self.device_handler.on_federation_query_user_devices(user_id)
  676. return 200, keys
  677. @trace
  678. async def on_claim_client_keys(
  679. self, origin: str, content: JsonDict
  680. ) -> Dict[str, Any]:
  681. query = []
  682. for user_id, device_keys in content.get("one_time_keys", {}).items():
  683. for device_id, algorithm in device_keys.items():
  684. query.append((user_id, device_id, algorithm))
  685. log_kv({"message": "Claiming one time keys.", "user, device pairs": query})
  686. results = await self.store.claim_e2e_one_time_keys(query)
  687. json_result: Dict[str, Dict[str, dict]] = {}
  688. for user_id, device_keys in results.items():
  689. for device_id, keys in device_keys.items():
  690. for key_id, json_str in keys.items():
  691. json_result.setdefault(user_id, {})[device_id] = {
  692. key_id: json_decoder.decode(json_str)
  693. }
  694. logger.info(
  695. "Claimed one-time-keys: %s",
  696. ",".join(
  697. (
  698. "%s for %s:%s" % (key_id, user_id, device_id)
  699. for user_id, user_keys in json_result.items()
  700. for device_id, device_keys in user_keys.items()
  701. for key_id, _ in device_keys.items()
  702. )
  703. ),
  704. )
  705. return {"one_time_keys": json_result}
  706. async def on_get_missing_events(
  707. self,
  708. origin: str,
  709. room_id: str,
  710. earliest_events: List[str],
  711. latest_events: List[str],
  712. limit: int,
  713. ) -> Dict[str, list]:
  714. with (await self._server_linearizer.queue((origin, room_id))):
  715. origin_host, _ = parse_server_name(origin)
  716. await self.check_server_matches_acl(origin_host, room_id)
  717. logger.debug(
  718. "on_get_missing_events: earliest_events: %r, latest_events: %r,"
  719. " limit: %d",
  720. earliest_events,
  721. latest_events,
  722. limit,
  723. )
  724. missing_events = await self.handler.on_get_missing_events(
  725. origin, room_id, earliest_events, latest_events, limit
  726. )
  727. if len(missing_events) < 5:
  728. logger.debug(
  729. "Returning %d events: %r", len(missing_events), missing_events
  730. )
  731. else:
  732. logger.debug("Returning %d events", len(missing_events))
  733. time_now = self._clock.time_msec()
  734. return {"events": [ev.get_pdu_json(time_now) for ev in missing_events]}
  735. @log_function
  736. async def on_openid_userinfo(self, token: str) -> Optional[str]:
  737. ts_now_ms = self._clock.time_msec()
  738. return await self.store.get_user_id_for_open_id_token(token, ts_now_ms)
  739. def _transaction_dict_from_pdus(self, pdu_list: List[EventBase]) -> JsonDict:
  740. """Returns a new Transaction containing the given PDUs suitable for
  741. transmission.
  742. """
  743. time_now = self._clock.time_msec()
  744. pdus = [p.get_pdu_json(time_now) for p in pdu_list]
  745. return Transaction(
  746. # Just need a dummy transaction ID and destination since it won't be used.
  747. transaction_id="",
  748. origin=self.server_name,
  749. pdus=pdus,
  750. origin_server_ts=int(time_now),
  751. destination="",
  752. ).get_dict()
  753. async def _handle_received_pdu(self, origin: str, pdu: EventBase) -> None:
  754. """Process a PDU received in a federation /send/ transaction.
  755. If the event is invalid, then this method throws a FederationError.
  756. (The error will then be logged and sent back to the sender (which
  757. probably won't do anything with it), and other events in the
  758. transaction will be processed as normal).
  759. It is likely that we'll then receive other events which refer to
  760. this rejected_event in their prev_events, etc. When that happens,
  761. we'll attempt to fetch the rejected event again, which will presumably
  762. fail, so those second-generation events will also get rejected.
  763. Eventually, we get to the point where there are more than 10 events
  764. between any new events and the original rejected event. Since we
  765. only try to backfill 10 events deep on received pdu, we then accept the
  766. new event, possibly introducing a discontinuity in the DAG, with new
  767. forward extremities, so normal service is approximately returned,
  768. until we try to backfill across the discontinuity.
  769. Args:
  770. origin: server which sent the pdu
  771. pdu: received pdu
  772. Raises: FederationError if the signatures / hash do not match, or
  773. if the event was unacceptable for any other reason (eg, too large,
  774. too many prev_events, couldn't find the prev_events)
  775. """
  776. # We've already checked that we know the room version by this point
  777. room_version = await self.store.get_room_version(pdu.room_id)
  778. # Check signature.
  779. try:
  780. pdu = await self._check_sigs_and_hash(room_version, pdu)
  781. except SynapseError as e:
  782. raise FederationError("ERROR", e.code, e.msg, affected=pdu.event_id)
  783. # Add the event to our staging area
  784. await self.store.insert_received_event_to_staging(origin, pdu)
  785. # Try and acquire the processing lock for the room, if we get it start a
  786. # background process for handling the events in the room.
  787. lock = await self.store.try_acquire_lock(
  788. _INBOUND_EVENT_HANDLING_LOCK_NAME, pdu.room_id
  789. )
  790. if lock:
  791. self._process_incoming_pdus_in_room_inner(
  792. pdu.room_id, room_version, lock, origin, pdu
  793. )
  794. @wrap_as_background_process("_process_incoming_pdus_in_room_inner")
  795. async def _process_incoming_pdus_in_room_inner(
  796. self,
  797. room_id: str,
  798. room_version: RoomVersion,
  799. lock: Lock,
  800. latest_origin: Optional[str] = None,
  801. latest_event: Optional[EventBase] = None,
  802. ) -> None:
  803. """Process events in the staging area for the given room.
  804. The latest_origin and latest_event args are the latest origin and event
  805. received (or None to simply pull the next event from the database).
  806. """
  807. # The common path is for the event we just received be the only event in
  808. # the room, so instead of pulling the event out of the DB and parsing
  809. # the event we just pull out the next event ID and check if that matches.
  810. if latest_event is not None and latest_origin is not None:
  811. result = await self.store.get_next_staged_event_id_for_room(room_id)
  812. if result is None:
  813. latest_origin = None
  814. latest_event = None
  815. else:
  816. next_origin, next_event_id = result
  817. if (
  818. next_origin != latest_origin
  819. or next_event_id != latest_event.event_id
  820. ):
  821. latest_origin = None
  822. latest_event = None
  823. if latest_origin is None or latest_event is None:
  824. next = await self.store.get_next_staged_event_for_room(
  825. room_id, room_version
  826. )
  827. if not next:
  828. await lock.release()
  829. return
  830. origin, event = next
  831. else:
  832. origin = latest_origin
  833. event = latest_event
  834. # We loop round until there are no more events in the room in the
  835. # staging area, or we fail to get the lock (which means another process
  836. # has started processing).
  837. while True:
  838. async with lock:
  839. logger.info("handling received PDU: %s", event)
  840. try:
  841. with nested_logging_context(event.event_id):
  842. await self._federation_event_handler.on_receive_pdu(
  843. origin, event
  844. )
  845. except FederationError as e:
  846. # XXX: Ideally we'd inform the remote we failed to process
  847. # the event, but we can't return an error in the transaction
  848. # response (as we've already responded).
  849. logger.warning("Error handling PDU %s: %s", event.event_id, e)
  850. except Exception:
  851. f = failure.Failure()
  852. logger.error(
  853. "Failed to handle PDU %s",
  854. event.event_id,
  855. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
  856. )
  857. received_ts = await self.store.remove_received_event_from_staging(
  858. origin, event.event_id
  859. )
  860. if received_ts is not None:
  861. pdu_process_time.observe(
  862. (self._clock.time_msec() - received_ts) / 1000
  863. )
  864. # We need to do this check outside the lock to avoid a race between
  865. # a new event being inserted by another instance and it attempting
  866. # to acquire the lock.
  867. next = await self.store.get_next_staged_event_for_room(
  868. room_id, room_version
  869. )
  870. if not next:
  871. break
  872. origin, event = next
  873. # Prune the event queue if it's getting large.
  874. #
  875. # We do this *after* handling the first event as the common case is
  876. # that the queue is empty (/has the single event in), and so there's
  877. # no need to do this check.
  878. pruned = await self.store.prune_staged_events_in_room(room_id, room_version)
  879. if pruned:
  880. # If we have pruned the queue check we need to refetch the next
  881. # event to handle.
  882. next = await self.store.get_next_staged_event_for_room(
  883. room_id, room_version
  884. )
  885. if not next:
  886. break
  887. origin, event = next
  888. new_lock = await self.store.try_acquire_lock(
  889. _INBOUND_EVENT_HANDLING_LOCK_NAME, room_id
  890. )
  891. if not new_lock:
  892. return
  893. lock = new_lock
  894. def __str__(self) -> str:
  895. return "<ReplicationLayer(%s)>" % self.server_name
  896. async def exchange_third_party_invite(
  897. self, sender_user_id: str, target_user_id: str, room_id: str, signed: Dict
  898. ) -> None:
  899. await self.handler.exchange_third_party_invite(
  900. sender_user_id, target_user_id, room_id, signed
  901. )
  902. async def on_exchange_third_party_invite_request(self, event_dict: Dict) -> None:
  903. await self.handler.on_exchange_third_party_invite_request(event_dict)
  904. async def check_server_matches_acl(self, server_name: str, room_id: str) -> None:
  905. """Check if the given server is allowed by the server ACLs in the room
  906. Args:
  907. server_name: name of server, *without any port part*
  908. room_id: ID of the room to check
  909. Raises:
  910. AuthError if the server does not match the ACL
  911. """
  912. state_ids = await self.store.get_current_state_ids(room_id)
  913. acl_event_id = state_ids.get((EventTypes.ServerACL, ""))
  914. if not acl_event_id:
  915. return
  916. acl_event = await self.store.get_event(acl_event_id)
  917. if server_matches_acl_event(server_name, acl_event):
  918. return
  919. raise AuthError(code=403, msg="Server is banned from room")
  920. def server_matches_acl_event(server_name: str, acl_event: EventBase) -> bool:
  921. """Check if the given server is allowed by the ACL event
  922. Args:
  923. server_name: name of server, without any port part
  924. acl_event: m.room.server_acl event
  925. Returns:
  926. True if this server is allowed by the ACLs
  927. """
  928. logger.debug("Checking %s against acl %s", server_name, acl_event.content)
  929. # first of all, check if literal IPs are blocked, and if so, whether the
  930. # server name is a literal IP
  931. allow_ip_literals = acl_event.content.get("allow_ip_literals", True)
  932. if not isinstance(allow_ip_literals, bool):
  933. logger.warning("Ignoring non-bool allow_ip_literals flag")
  934. allow_ip_literals = True
  935. if not allow_ip_literals:
  936. # check for ipv6 literals. These start with '['.
  937. if server_name[0] == "[":
  938. return False
  939. # check for ipv4 literals. We can just lift the routine from twisted.
  940. if isIPAddress(server_name):
  941. return False
  942. # next, check the deny list
  943. deny = acl_event.content.get("deny", [])
  944. if not isinstance(deny, (list, tuple)):
  945. logger.warning("Ignoring non-list deny ACL %s", deny)
  946. deny = []
  947. for e in deny:
  948. if _acl_entry_matches(server_name, e):
  949. # logger.info("%s matched deny rule %s", server_name, e)
  950. return False
  951. # then the allow list.
  952. allow = acl_event.content.get("allow", [])
  953. if not isinstance(allow, (list, tuple)):
  954. logger.warning("Ignoring non-list allow ACL %s", allow)
  955. allow = []
  956. for e in allow:
  957. if _acl_entry_matches(server_name, e):
  958. # logger.info("%s matched allow rule %s", server_name, e)
  959. return True
  960. # everything else should be rejected.
  961. # logger.info("%s fell through", server_name)
  962. return False
  963. def _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:
  964. if not isinstance(acl_entry, str):
  965. logger.warning(
  966. "Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry)
  967. )
  968. return False
  969. regex = glob_to_regex(acl_entry)
  970. return bool(regex.match(server_name))
  971. class FederationHandlerRegistry:
  972. """Allows classes to register themselves as handlers for a given EDU or
  973. query type for incoming federation traffic.
  974. """
  975. def __init__(self, hs: "HomeServer"):
  976. self.config = hs.config
  977. self.clock = hs.get_clock()
  978. self._instance_name = hs.get_instance_name()
  979. # These are safe to load in monolith mode, but will explode if we try
  980. # and use them. However we have guards before we use them to ensure that
  981. # we don't route to ourselves, and in monolith mode that will always be
  982. # the case.
  983. self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)
  984. self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)
  985. self.edu_handlers: Dict[str, Callable[[str, dict], Awaitable[None]]] = {}
  986. self.query_handlers: Dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
  987. # Map from type to instance names that we should route EDU handling to.
  988. # We randomly choose one instance from the list to route to for each new
  989. # EDU received.
  990. self._edu_type_to_instance: Dict[str, List[str]] = {}
  991. def register_edu_handler(
  992. self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]
  993. ) -> None:
  994. """Sets the handler callable that will be used to handle an incoming
  995. federation EDU of the given type.
  996. Args:
  997. edu_type: The type of the incoming EDU to register handler for
  998. handler: A callable invoked on incoming EDU
  999. of the given type. The arguments are the origin server name and
  1000. the EDU contents.
  1001. """
  1002. if edu_type in self.edu_handlers:
  1003. raise KeyError("Already have an EDU handler for %s" % (edu_type,))
  1004. logger.info("Registering federation EDU handler for %r", edu_type)
  1005. self.edu_handlers[edu_type] = handler
  1006. def register_query_handler(
  1007. self, query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
  1008. ) -> None:
  1009. """Sets the handler callable that will be used to handle an incoming
  1010. federation query of the given type.
  1011. Args:
  1012. query_type: Category name of the query, which should match
  1013. the string used by make_query.
  1014. handler: Invoked to handle
  1015. incoming queries of this type. The return will be yielded
  1016. on and the result used as the response to the query request.
  1017. """
  1018. if query_type in self.query_handlers:
  1019. raise KeyError("Already have a Query handler for %s" % (query_type,))
  1020. logger.info("Registering federation query handler for %r", query_type)
  1021. self.query_handlers[query_type] = handler
  1022. def register_instances_for_edu(
  1023. self, edu_type: str, instance_names: List[str]
  1024. ) -> None:
  1025. """Register that the EDU handler is on multiple instances."""
  1026. self._edu_type_to_instance[edu_type] = instance_names
  1027. async def on_edu(self, edu_type: str, origin: str, content: dict) -> None:
  1028. if not self.config.server.use_presence and edu_type == EduTypes.Presence:
  1029. return
  1030. # Check if we have a handler on this instance
  1031. handler = self.edu_handlers.get(edu_type)
  1032. if handler:
  1033. with start_active_span_from_edu(content, "handle_edu"):
  1034. try:
  1035. await handler(origin, content)
  1036. except SynapseError as e:
  1037. logger.info("Failed to handle edu %r: %r", edu_type, e)
  1038. except Exception:
  1039. logger.exception("Failed to handle edu %r", edu_type)
  1040. return
  1041. # Check if we can route it somewhere else that isn't us
  1042. instances = self._edu_type_to_instance.get(edu_type, ["master"])
  1043. if self._instance_name not in instances:
  1044. # Pick an instance randomly so that we don't overload one.
  1045. route_to = random.choice(instances)
  1046. try:
  1047. await self._send_edu(
  1048. instance_name=route_to,
  1049. edu_type=edu_type,
  1050. origin=origin,
  1051. content=content,
  1052. )
  1053. except SynapseError as e:
  1054. logger.info("Failed to handle edu %r: %r", edu_type, e)
  1055. except Exception:
  1056. logger.exception("Failed to handle edu %r", edu_type)
  1057. return
  1058. # Oh well, let's just log and move on.
  1059. logger.warning("No handler registered for EDU type %s", edu_type)
  1060. async def on_query(self, query_type: str, args: dict) -> JsonDict:
  1061. handler = self.query_handlers.get(query_type)
  1062. if handler:
  1063. return await handler(args)
  1064. # Check if we can route it somewhere else that isn't us
  1065. if self._instance_name == "master":
  1066. return await self._get_query_client(query_type=query_type, args=args)
  1067. # Uh oh, no handler! Let's raise an exception so the request returns an
  1068. # error.
  1069. logger.warning("No handler registered for query type %s", query_type)
  1070. raise NotFoundError("No handler for Query type '%s'" % (query_type,))