federation_server.py 50 KB

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