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

986 lines
37 KiB

  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
  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.ratelimiting import Ratelimiter
  45. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  46. from synapse.events import EventBase
  47. from synapse.federation.federation_base import FederationBase, event_from_pdu_json
  48. from synapse.federation.persistence import TransactionActions
  49. from synapse.federation.units import Edu, Transaction
  50. from synapse.http.servlet import assert_params_in_dict
  51. from synapse.logging.context import (
  52. make_deferred_yieldable,
  53. nested_logging_context,
  54. run_in_background,
  55. )
  56. from synapse.logging.opentracing import log_kv, start_active_span_from_edu, trace
  57. from synapse.logging.utils import log_function
  58. from synapse.replication.http.federation import (
  59. ReplicationFederationSendEduRestServlet,
  60. ReplicationGetQueryRestServlet,
  61. )
  62. from synapse.types import JsonDict
  63. from synapse.util import glob_to_regex, json_decoder, unwrapFirstError
  64. from synapse.util.async_helpers import Linearizer, concurrently_execute
  65. from synapse.util.caches.response_cache import ResponseCache
  66. from synapse.util.stringutils import parse_server_name
  67. if TYPE_CHECKING:
  68. from synapse.server import HomeServer
  69. # when processing incoming transactions, we try to handle multiple rooms in
  70. # parallel, up to this limit.
  71. TRANSACTION_CONCURRENCY_LIMIT = 10
  72. logger = logging.getLogger(__name__)
  73. received_pdus_counter = Counter("synapse_federation_server_received_pdus", "")
  74. received_edus_counter = Counter("synapse_federation_server_received_edus", "")
  75. received_queries_counter = Counter(
  76. "synapse_federation_server_received_queries", "", ["type"]
  77. )
  78. pdu_process_time = Histogram(
  79. "synapse_federation_server_pdu_process_time",
  80. "Time taken to process an event",
  81. )
  82. last_pdu_ts_metric = Gauge(
  83. "synapse_federation_last_received_pdu_time",
  84. "The timestamp of the last PDU which was successfully received from the given domain",
  85. labelnames=("server_name",),
  86. )
  87. class FederationServer(FederationBase):
  88. def __init__(self, hs: "HomeServer"):
  89. super().__init__(hs)
  90. self.auth = hs.get_auth()
  91. self.handler = hs.get_federation_handler()
  92. self.state = hs.get_state_handler()
  93. self.device_handler = hs.get_device_handler()
  94. # Ensure the following handlers are loaded since they register callbacks
  95. # with FederationHandlerRegistry.
  96. hs.get_directory_handler()
  97. self._server_linearizer = Linearizer("fed_server")
  98. # origins that we are currently processing a transaction from.
  99. # a dict from origin to txn id.
  100. self._active_transactions = {} # type: Dict[str, str]
  101. # We cache results for transaction with the same ID
  102. self._transaction_resp_cache = ResponseCache(
  103. hs.get_clock(), "fed_txn_handler", timeout_ms=30000
  104. ) # type: ResponseCache[Tuple[str, str]]
  105. self.transaction_actions = TransactionActions(self.store)
  106. self.registry = hs.get_federation_registry()
  107. # We cache responses to state queries, as they take a while and often
  108. # come in waves.
  109. self._state_resp_cache = ResponseCache(
  110. hs.get_clock(), "state_resp", timeout_ms=30000
  111. ) # type: ResponseCache[Tuple[str, str]]
  112. self._state_ids_resp_cache = ResponseCache(
  113. hs.get_clock(), "state_ids_resp", timeout_ms=30000
  114. ) # type: ResponseCache[Tuple[str, str]]
  115. self._federation_metrics_domains = (
  116. hs.get_config().federation.federation_metrics_domains
  117. )
  118. async def on_backfill_request(
  119. self, origin: str, room_id: str, versions: List[str], limit: int
  120. ) -> Tuple[int, Dict[str, Any]]:
  121. with (await self._server_linearizer.queue((origin, room_id))):
  122. origin_host, _ = parse_server_name(origin)
  123. await self.check_server_matches_acl(origin_host, room_id)
  124. pdus = await self.handler.on_backfill_request(
  125. origin, room_id, versions, limit
  126. )
  127. res = self._transaction_from_pdus(pdus).get_dict()
  128. return 200, res
  129. async def on_incoming_transaction(
  130. self, origin: str, transaction_data: JsonDict
  131. ) -> Tuple[int, Dict[str, Any]]:
  132. # keep this as early as possible to make the calculated origin ts as
  133. # accurate as possible.
  134. request_time = self._clock.time_msec()
  135. transaction = Transaction(**transaction_data)
  136. transaction_id = transaction.transaction_id # type: ignore
  137. if not transaction_id:
  138. raise Exception("Transaction missing transaction_id")
  139. logger.debug("[%s] Got transaction", transaction_id)
  140. # Reject malformed transactions early: reject if too many PDUs/EDUs
  141. if len(transaction.pdus) > 50 or ( # type: ignore
  142. hasattr(transaction, "edus") and len(transaction.edus) > 100 # type: ignore
  143. ):
  144. logger.info("Transaction PDU or EDU count too large. Returning 400")
  145. return 400, {}
  146. # we only process one transaction from each origin at a time. We need to do
  147. # this check here, rather than in _on_incoming_transaction_inner so that we
  148. # don't cache the rejection in _transaction_resp_cache (so that if the txn
  149. # arrives again later, we can process it).
  150. current_transaction = self._active_transactions.get(origin)
  151. if current_transaction and current_transaction != transaction_id:
  152. logger.warning(
  153. "Received another txn %s from %s while still processing %s",
  154. transaction_id,
  155. origin,
  156. current_transaction,
  157. )
  158. return 429, {
  159. "errcode": Codes.UNKNOWN,
  160. "error": "Too many concurrent transactions",
  161. }
  162. # CRITICAL SECTION: we must now not await until we populate _active_transactions
  163. # in _on_incoming_transaction_inner.
  164. # We wrap in a ResponseCache so that we de-duplicate retried
  165. # transactions.
  166. return await self._transaction_resp_cache.wrap(
  167. (origin, transaction_id),
  168. self._on_incoming_transaction_inner,
  169. origin,
  170. transaction,
  171. request_time,
  172. )
  173. async def _on_incoming_transaction_inner(
  174. self, origin: str, transaction: Transaction, request_time: int
  175. ) -> Tuple[int, Dict[str, Any]]:
  176. # CRITICAL SECTION: the first thing we must do (before awaiting) is
  177. # add an entry to _active_transactions.
  178. assert origin not in self._active_transactions
  179. self._active_transactions[origin] = transaction.transaction_id # type: ignore
  180. try:
  181. result = await self._handle_incoming_transaction(
  182. origin, transaction, request_time
  183. )
  184. return result
  185. finally:
  186. del self._active_transactions[origin]
  187. async def _handle_incoming_transaction(
  188. self, origin: str, transaction: Transaction, request_time: int
  189. ) -> Tuple[int, Dict[str, Any]]:
  190. """Process an incoming transaction and return the HTTP response
  191. Args:
  192. origin: the server making the request
  193. transaction: incoming transaction
  194. request_time: timestamp that the HTTP request arrived at
  195. Returns:
  196. HTTP response code and body
  197. """
  198. response = await self.transaction_actions.have_responded(origin, transaction)
  199. if response:
  200. logger.debug(
  201. "[%s] We've already responded to this request",
  202. transaction.transaction_id, # type: ignore
  203. )
  204. return response
  205. logger.debug("[%s] Transaction is new", transaction.transaction_id) # type: ignore
  206. # We process PDUs and EDUs in parallel. This is important as we don't
  207. # want to block things like to device messages from reaching clients
  208. # behind the potentially expensive handling of PDUs.
  209. pdu_results, _ = await make_deferred_yieldable(
  210. defer.gatherResults(
  211. [
  212. run_in_background(
  213. self._handle_pdus_in_txn, origin, transaction, request_time
  214. ),
  215. run_in_background(self._handle_edus_in_txn, origin, transaction),
  216. ],
  217. consumeErrors=True,
  218. ).addErrback(unwrapFirstError)
  219. )
  220. response = {"pdus": pdu_results}
  221. logger.debug("Returning: %s", str(response))
  222. await self.transaction_actions.set_response(origin, transaction, 200, response)
  223. return 200, response
  224. async def _handle_pdus_in_txn(
  225. self, origin: str, transaction: Transaction, request_time: int
  226. ) -> Dict[str, dict]:
  227. """Process the PDUs in a received transaction.
  228. Args:
  229. origin: the server making the request
  230. transaction: incoming transaction
  231. request_time: timestamp that the HTTP request arrived at
  232. Returns:
  233. A map from event ID of a processed PDU to any errors we should
  234. report back to the sending server.
  235. """
  236. received_pdus_counter.inc(len(transaction.pdus)) # type: ignore
  237. origin_host, _ = parse_server_name(origin)
  238. pdus_by_room = {} # type: Dict[str, List[EventBase]]
  239. newest_pdu_ts = 0
  240. for p in transaction.pdus: # type: ignore
  241. # FIXME (richardv): I don't think this works:
  242. # https://github.com/matrix-org/synapse/issues/8429
  243. if "unsigned" in p:
  244. unsigned = p["unsigned"]
  245. if "age" in unsigned:
  246. p["age"] = unsigned["age"]
  247. if "age" in p:
  248. p["age_ts"] = request_time - int(p["age"])
  249. del p["age"]
  250. # We try and pull out an event ID so that if later checks fail we
  251. # can log something sensible. We don't mandate an event ID here in
  252. # case future event formats get rid of the key.
  253. possible_event_id = p.get("event_id", "<Unknown>")
  254. # Now we get the room ID so that we can check that we know the
  255. # version of the room.
  256. room_id = p.get("room_id")
  257. if not room_id:
  258. logger.info(
  259. "Ignoring PDU as does not have a room_id. Event ID: %s",
  260. possible_event_id,
  261. )
  262. continue
  263. try:
  264. room_version = await self.store.get_room_version(room_id)
  265. except NotFoundError:
  266. logger.info("Ignoring PDU for unknown room_id: %s", room_id)
  267. continue
  268. except UnsupportedRoomVersionError as e:
  269. # this can happen if support for a given room version is withdrawn,
  270. # so that we still get events for said room.
  271. logger.info("Ignoring PDU: %s", e)
  272. continue
  273. event = event_from_pdu_json(p, room_version)
  274. pdus_by_room.setdefault(room_id, []).append(event)
  275. if event.origin_server_ts > newest_pdu_ts:
  276. newest_pdu_ts = event.origin_server_ts
  277. pdu_results = {}
  278. # we can process different rooms in parallel (which is useful if they
  279. # require callouts to other servers to fetch missing events), but
  280. # impose a limit to avoid going too crazy with ram/cpu.
  281. async def process_pdus_for_room(room_id: str):
  282. with nested_logging_context(room_id):
  283. logger.debug("Processing PDUs for %s", room_id)
  284. try:
  285. await self.check_server_matches_acl(origin_host, room_id)
  286. except AuthError as e:
  287. logger.warning(
  288. "Ignoring PDUs for room %s from banned server", room_id
  289. )
  290. for pdu in pdus_by_room[room_id]:
  291. event_id = pdu.event_id
  292. pdu_results[event_id] = e.error_dict()
  293. return
  294. for pdu in pdus_by_room[room_id]:
  295. pdu_results[pdu.event_id] = await process_pdu(pdu)
  296. async def process_pdu(pdu: EventBase) -> JsonDict:
  297. event_id = pdu.event_id
  298. with pdu_process_time.time():
  299. with nested_logging_context(event_id):
  300. try:
  301. await self._handle_received_pdu(origin, pdu)
  302. return {}
  303. except FederationError as e:
  304. logger.warning("Error handling PDU %s: %s", event_id, e)
  305. return {"error": str(e)}
  306. except Exception as e:
  307. f = failure.Failure()
  308. logger.error(
  309. "Failed to handle PDU %s",
  310. event_id,
  311. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
  312. )
  313. return {"error": str(e)}
  314. await concurrently_execute(
  315. process_pdus_for_room, pdus_by_room.keys(), TRANSACTION_CONCURRENCY_LIMIT
  316. )
  317. if newest_pdu_ts and origin in self._federation_metrics_domains:
  318. last_pdu_ts_metric.labels(server_name=origin).set(newest_pdu_ts / 1000)
  319. return pdu_results
  320. async def _handle_edus_in_txn(self, origin: str, transaction: Transaction):
  321. """Process the EDUs in a received transaction."""
  322. async def _process_edu(edu_dict):
  323. received_edus_counter.inc()
  324. edu = Edu(
  325. origin=origin,
  326. destination=self.server_name,
  327. edu_type=edu_dict["edu_type"],
  328. content=edu_dict["content"],
  329. )
  330. await self.registry.on_edu(edu.edu_type, origin, edu.content)
  331. await concurrently_execute(
  332. _process_edu,
  333. getattr(transaction, "edus", []),
  334. TRANSACTION_CONCURRENCY_LIMIT,
  335. )
  336. async def on_room_state_request(
  337. self, origin: str, room_id: str, event_id: str
  338. ) -> Tuple[int, Dict[str, Any]]:
  339. origin_host, _ = parse_server_name(origin)
  340. await self.check_server_matches_acl(origin_host, room_id)
  341. in_room = await self.auth.check_host_in_room(room_id, origin)
  342. if not in_room:
  343. raise AuthError(403, "Host not in room.")
  344. # we grab the linearizer to protect ourselves from servers which hammer
  345. # us. In theory we might already have the response to this query
  346. # in the cache so we could return it without waiting for the linearizer
  347. # - but that's non-trivial to get right, and anyway somewhat defeats
  348. # the point of the linearizer.
  349. with (await self._server_linearizer.queue((origin, room_id))):
  350. resp = dict(
  351. await self._state_resp_cache.wrap(
  352. (room_id, event_id),
  353. self._on_context_state_request_compute,
  354. room_id,
  355. event_id,
  356. )
  357. )
  358. room_version = await self.store.get_room_version_id(room_id)
  359. resp["room_version"] = room_version
  360. return 200, resp
  361. async def on_state_ids_request(
  362. self, origin: str, room_id: str, event_id: str
  363. ) -> Tuple[int, Dict[str, Any]]:
  364. if not event_id:
  365. raise NotImplementedError("Specify an event")
  366. origin_host, _ = parse_server_name(origin)
  367. await self.check_server_matches_acl(origin_host, room_id)
  368. in_room = await self.auth.check_host_in_room(room_id, origin)
  369. if not in_room:
  370. raise AuthError(403, "Host not in room.")
  371. resp = await self._state_ids_resp_cache.wrap(
  372. (room_id, event_id),
  373. self._on_state_ids_request_compute,
  374. room_id,
  375. event_id,
  376. )
  377. return 200, resp
  378. async def _on_state_ids_request_compute(self, room_id, event_id):
  379. state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
  380. auth_chain_ids = await self.store.get_auth_chain_ids(room_id, state_ids)
  381. return {"pdu_ids": state_ids, "auth_chain_ids": auth_chain_ids}
  382. async def _on_context_state_request_compute(
  383. self, room_id: str, event_id: str
  384. ) -> Dict[str, list]:
  385. if event_id:
  386. pdus = await self.handler.get_state_for_pdu(
  387. room_id, event_id
  388. ) # type: Iterable[EventBase]
  389. else:
  390. pdus = (await self.state.get_current_state(room_id)).values()
  391. auth_chain = await self.store.get_auth_chain(
  392. room_id, [pdu.event_id for pdu in pdus]
  393. )
  394. return {
  395. "pdus": [pdu.get_pdu_json() for pdu in pdus],
  396. "auth_chain": [pdu.get_pdu_json() for pdu in auth_chain],
  397. }
  398. async def on_pdu_request(
  399. self, origin: str, event_id: str
  400. ) -> Tuple[int, Union[JsonDict, str]]:
  401. pdu = await self.handler.get_persisted_pdu(origin, event_id)
  402. if pdu:
  403. return 200, self._transaction_from_pdus([pdu]).get_dict()
  404. else:
  405. return 404, ""
  406. async def on_query_request(
  407. self, query_type: str, args: Dict[str, str]
  408. ) -> Tuple[int, Dict[str, Any]]:
  409. received_queries_counter.labels(query_type).inc()
  410. resp = await self.registry.on_query(query_type, args)
  411. return 200, resp
  412. async def on_make_join_request(
  413. self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
  414. ) -> Dict[str, Any]:
  415. origin_host, _ = parse_server_name(origin)
  416. await self.check_server_matches_acl(origin_host, room_id)
  417. room_version = await self.store.get_room_version_id(room_id)
  418. if room_version not in supported_versions:
  419. logger.warning(
  420. "Room version %s not in %s", room_version, supported_versions
  421. )
  422. raise IncompatibleRoomVersionError(room_version=room_version)
  423. pdu = await self.handler.on_make_join_request(origin, room_id, user_id)
  424. time_now = self._clock.time_msec()
  425. return {"event": pdu.get_pdu_json(time_now), "room_version": room_version}
  426. async def on_invite_request(
  427. self, origin: str, content: JsonDict, room_version_id: str
  428. ) -> Dict[str, Any]:
  429. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  430. if not room_version:
  431. raise SynapseError(
  432. 400,
  433. "Homeserver does not support this room version",
  434. Codes.UNSUPPORTED_ROOM_VERSION,
  435. )
  436. pdu = event_from_pdu_json(content, room_version)
  437. origin_host, _ = parse_server_name(origin)
  438. await self.check_server_matches_acl(origin_host, pdu.room_id)
  439. pdu = await self._check_sigs_and_hash(room_version, pdu)
  440. ret_pdu = await self.handler.on_invite_request(origin, pdu, room_version)
  441. time_now = self._clock.time_msec()
  442. return {"event": ret_pdu.get_pdu_json(time_now)}
  443. async def on_send_join_request(
  444. self, origin: str, content: JsonDict
  445. ) -> Dict[str, Any]:
  446. logger.debug("on_send_join_request: content: %s", content)
  447. assert_params_in_dict(content, ["room_id"])
  448. room_version = await self.store.get_room_version(content["room_id"])
  449. pdu = event_from_pdu_json(content, room_version)
  450. origin_host, _ = parse_server_name(origin)
  451. await self.check_server_matches_acl(origin_host, pdu.room_id)
  452. logger.debug("on_send_join_request: pdu sigs: %s", pdu.signatures)
  453. pdu = await self._check_sigs_and_hash(room_version, pdu)
  454. res_pdus = await self.handler.on_send_join_request(origin, pdu)
  455. time_now = self._clock.time_msec()
  456. return {
  457. "state": [p.get_pdu_json(time_now) for p in res_pdus["state"]],
  458. "auth_chain": [p.get_pdu_json(time_now) for p in res_pdus["auth_chain"]],
  459. }
  460. async def on_make_leave_request(
  461. self, origin: str, room_id: str, user_id: str
  462. ) -> Dict[str, Any]:
  463. origin_host, _ = parse_server_name(origin)
  464. await self.check_server_matches_acl(origin_host, room_id)
  465. pdu = await self.handler.on_make_leave_request(origin, room_id, user_id)
  466. room_version = await self.store.get_room_version_id(room_id)
  467. time_now = self._clock.time_msec()
  468. return {"event": pdu.get_pdu_json(time_now), "room_version": room_version}
  469. async def on_send_leave_request(self, origin: str, content: JsonDict) -> dict:
  470. logger.debug("on_send_leave_request: content: %s", content)
  471. assert_params_in_dict(content, ["room_id"])
  472. room_version = await self.store.get_room_version(content["room_id"])
  473. pdu = event_from_pdu_json(content, room_version)
  474. origin_host, _ = parse_server_name(origin)
  475. await self.check_server_matches_acl(origin_host, pdu.room_id)
  476. logger.debug("on_send_leave_request: pdu sigs: %s", pdu.signatures)
  477. pdu = await self._check_sigs_and_hash(room_version, pdu)
  478. await self.handler.on_send_leave_request(origin, pdu)
  479. return {}
  480. async def on_event_auth(
  481. self, origin: str, room_id: str, event_id: str
  482. ) -> Tuple[int, Dict[str, Any]]:
  483. with (await self._server_linearizer.queue((origin, room_id))):
  484. origin_host, _ = parse_server_name(origin)
  485. await self.check_server_matches_acl(origin_host, room_id)
  486. time_now = self._clock.time_msec()
  487. auth_pdus = await self.handler.on_event_auth(event_id)
  488. res = {"auth_chain": [a.get_pdu_json(time_now) for a in auth_pdus]}
  489. return 200, res
  490. @log_function
  491. async def on_query_client_keys(
  492. self, origin: str, content: Dict[str, str]
  493. ) -> Tuple[int, Dict[str, Any]]:
  494. return await self.on_query_request("client_keys", content)
  495. async def on_query_user_devices(
  496. self, origin: str, user_id: str
  497. ) -> Tuple[int, Dict[str, Any]]:
  498. keys = await self.device_handler.on_federation_query_user_devices(user_id)
  499. return 200, keys
  500. @trace
  501. async def on_claim_client_keys(
  502. self, origin: str, content: JsonDict
  503. ) -> Dict[str, Any]:
  504. query = []
  505. for user_id, device_keys in content.get("one_time_keys", {}).items():
  506. for device_id, algorithm in device_keys.items():
  507. query.append((user_id, device_id, algorithm))
  508. log_kv({"message": "Claiming one time keys.", "user, device pairs": query})
  509. results = await self.store.claim_e2e_one_time_keys(query)
  510. json_result = {} # type: Dict[str, Dict[str, dict]]
  511. for user_id, device_keys in results.items():
  512. for device_id, keys in device_keys.items():
  513. for key_id, json_str in keys.items():
  514. json_result.setdefault(user_id, {})[device_id] = {
  515. key_id: json_decoder.decode(json_str)
  516. }
  517. logger.info(
  518. "Claimed one-time-keys: %s",
  519. ",".join(
  520. (
  521. "%s for %s:%s" % (key_id, user_id, device_id)
  522. for user_id, user_keys in json_result.items()
  523. for device_id, device_keys in user_keys.items()
  524. for key_id, _ in device_keys.items()
  525. )
  526. ),
  527. )
  528. return {"one_time_keys": json_result}
  529. async def on_get_missing_events(
  530. self,
  531. origin: str,
  532. room_id: str,
  533. earliest_events: List[str],
  534. latest_events: List[str],
  535. limit: int,
  536. ) -> Dict[str, list]:
  537. with (await self._server_linearizer.queue((origin, room_id))):
  538. origin_host, _ = parse_server_name(origin)
  539. await self.check_server_matches_acl(origin_host, room_id)
  540. logger.debug(
  541. "on_get_missing_events: earliest_events: %r, latest_events: %r,"
  542. " limit: %d",
  543. earliest_events,
  544. latest_events,
  545. limit,
  546. )
  547. missing_events = await self.handler.on_get_missing_events(
  548. origin, room_id, earliest_events, latest_events, limit
  549. )
  550. if len(missing_events) < 5:
  551. logger.debug(
  552. "Returning %d events: %r", len(missing_events), missing_events
  553. )
  554. else:
  555. logger.debug("Returning %d events", len(missing_events))
  556. time_now = self._clock.time_msec()
  557. return {"events": [ev.get_pdu_json(time_now) for ev in missing_events]}
  558. @log_function
  559. async def on_openid_userinfo(self, token: str) -> Optional[str]:
  560. ts_now_ms = self._clock.time_msec()
  561. return await self.store.get_user_id_for_open_id_token(token, ts_now_ms)
  562. def _transaction_from_pdus(self, pdu_list: List[EventBase]) -> Transaction:
  563. """Returns a new Transaction containing the given PDUs suitable for
  564. transmission.
  565. """
  566. time_now = self._clock.time_msec()
  567. pdus = [p.get_pdu_json(time_now) for p in pdu_list]
  568. return Transaction(
  569. origin=self.server_name,
  570. pdus=pdus,
  571. origin_server_ts=int(time_now),
  572. destination=None,
  573. )
  574. async def _handle_received_pdu(self, origin: str, pdu: EventBase) -> None:
  575. """Process a PDU received in a federation /send/ transaction.
  576. If the event is invalid, then this method throws a FederationError.
  577. (The error will then be logged and sent back to the sender (which
  578. probably won't do anything with it), and other events in the
  579. transaction will be processed as normal).
  580. It is likely that we'll then receive other events which refer to
  581. this rejected_event in their prev_events, etc. When that happens,
  582. we'll attempt to fetch the rejected event again, which will presumably
  583. fail, so those second-generation events will also get rejected.
  584. Eventually, we get to the point where there are more than 10 events
  585. between any new events and the original rejected event. Since we
  586. only try to backfill 10 events deep on received pdu, we then accept the
  587. new event, possibly introducing a discontinuity in the DAG, with new
  588. forward extremities, so normal service is approximately returned,
  589. until we try to backfill across the discontinuity.
  590. Args:
  591. origin: server which sent the pdu
  592. pdu: received pdu
  593. Raises: FederationError if the signatures / hash do not match, or
  594. if the event was unacceptable for any other reason (eg, too large,
  595. too many prev_events, couldn't find the prev_events)
  596. """
  597. # We've already checked that we know the room version by this point
  598. room_version = await self.store.get_room_version(pdu.room_id)
  599. # Check signature.
  600. try:
  601. pdu = await self._check_sigs_and_hash(room_version, pdu)
  602. except SynapseError as e:
  603. raise FederationError("ERROR", e.code, e.msg, affected=pdu.event_id)
  604. await self.handler.on_receive_pdu(origin, pdu, sent_to_us_directly=True)
  605. def __str__(self) -> str:
  606. return "<ReplicationLayer(%s)>" % self.server_name
  607. async def exchange_third_party_invite(
  608. self, sender_user_id: str, target_user_id: str, room_id: str, signed: Dict
  609. ) -> None:
  610. await self.handler.exchange_third_party_invite(
  611. sender_user_id, target_user_id, room_id, signed
  612. )
  613. async def on_exchange_third_party_invite_request(self, event_dict: Dict) -> None:
  614. await self.handler.on_exchange_third_party_invite_request(event_dict)
  615. async def check_server_matches_acl(self, server_name: str, room_id: str) -> None:
  616. """Check if the given server is allowed by the server ACLs in the room
  617. Args:
  618. server_name: name of server, *without any port part*
  619. room_id: ID of the room to check
  620. Raises:
  621. AuthError if the server does not match the ACL
  622. """
  623. state_ids = await self.store.get_current_state_ids(room_id)
  624. acl_event_id = state_ids.get((EventTypes.ServerACL, ""))
  625. if not acl_event_id:
  626. return
  627. acl_event = await self.store.get_event(acl_event_id)
  628. if server_matches_acl_event(server_name, acl_event):
  629. return
  630. raise AuthError(code=403, msg="Server is banned from room")
  631. def server_matches_acl_event(server_name: str, acl_event: EventBase) -> bool:
  632. """Check if the given server is allowed by the ACL event
  633. Args:
  634. server_name: name of server, without any port part
  635. acl_event: m.room.server_acl event
  636. Returns:
  637. True if this server is allowed by the ACLs
  638. """
  639. logger.debug("Checking %s against acl %s", server_name, acl_event.content)
  640. # first of all, check if literal IPs are blocked, and if so, whether the
  641. # server name is a literal IP
  642. allow_ip_literals = acl_event.content.get("allow_ip_literals", True)
  643. if not isinstance(allow_ip_literals, bool):
  644. logger.warning("Ignoring non-bool allow_ip_literals flag")
  645. allow_ip_literals = True
  646. if not allow_ip_literals:
  647. # check for ipv6 literals. These start with '['.
  648. if server_name[0] == "[":
  649. return False
  650. # check for ipv4 literals. We can just lift the routine from twisted.
  651. if isIPAddress(server_name):
  652. return False
  653. # next, check the deny list
  654. deny = acl_event.content.get("deny", [])
  655. if not isinstance(deny, (list, tuple)):
  656. logger.warning("Ignoring non-list deny ACL %s", deny)
  657. deny = []
  658. for e in deny:
  659. if _acl_entry_matches(server_name, e):
  660. # logger.info("%s matched deny rule %s", server_name, e)
  661. return False
  662. # then the allow list.
  663. allow = acl_event.content.get("allow", [])
  664. if not isinstance(allow, (list, tuple)):
  665. logger.warning("Ignoring non-list allow ACL %s", allow)
  666. allow = []
  667. for e in allow:
  668. if _acl_entry_matches(server_name, e):
  669. # logger.info("%s matched allow rule %s", server_name, e)
  670. return True
  671. # everything else should be rejected.
  672. # logger.info("%s fell through", server_name)
  673. return False
  674. def _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:
  675. if not isinstance(acl_entry, str):
  676. logger.warning(
  677. "Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry)
  678. )
  679. return False
  680. regex = glob_to_regex(acl_entry)
  681. return bool(regex.match(server_name))
  682. class FederationHandlerRegistry:
  683. """Allows classes to register themselves as handlers for a given EDU or
  684. query type for incoming federation traffic.
  685. """
  686. def __init__(self, hs: "HomeServer"):
  687. self.config = hs.config
  688. self.clock = hs.get_clock()
  689. self._instance_name = hs.get_instance_name()
  690. # These are safe to load in monolith mode, but will explode if we try
  691. # and use them. However we have guards before we use them to ensure that
  692. # we don't route to ourselves, and in monolith mode that will always be
  693. # the case.
  694. self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)
  695. self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)
  696. self.edu_handlers = (
  697. {}
  698. ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]]
  699. self.query_handlers = (
  700. {}
  701. ) # type: Dict[str, Callable[[dict], Awaitable[JsonDict]]]
  702. # Map from type to instance names that we should route EDU handling to.
  703. # We randomly choose one instance from the list to route to for each new
  704. # EDU received.
  705. self._edu_type_to_instance = {} # type: Dict[str, List[str]]
  706. # A rate limiter for incoming room key requests per origin.
  707. self._room_key_request_rate_limiter = Ratelimiter(
  708. store=hs.get_datastore(),
  709. clock=self.clock,
  710. rate_hz=self.config.rc_key_requests.per_second,
  711. burst_count=self.config.rc_key_requests.burst_count,
  712. )
  713. def register_edu_handler(
  714. self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]
  715. ) -> None:
  716. """Sets the handler callable that will be used to handle an incoming
  717. federation EDU of the given type.
  718. Args:
  719. edu_type: The type of the incoming EDU to register handler for
  720. handler: A callable invoked on incoming EDU
  721. of the given type. The arguments are the origin server name and
  722. the EDU contents.
  723. """
  724. if edu_type in self.edu_handlers:
  725. raise KeyError("Already have an EDU handler for %s" % (edu_type,))
  726. logger.info("Registering federation EDU handler for %r", edu_type)
  727. self.edu_handlers[edu_type] = handler
  728. def register_query_handler(
  729. self, query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
  730. ) -> None:
  731. """Sets the handler callable that will be used to handle an incoming
  732. federation query of the given type.
  733. Args:
  734. query_type: Category name of the query, which should match
  735. the string used by make_query.
  736. handler: Invoked to handle
  737. incoming queries of this type. The return will be yielded
  738. on and the result used as the response to the query request.
  739. """
  740. if query_type in self.query_handlers:
  741. raise KeyError("Already have a Query handler for %s" % (query_type,))
  742. logger.info("Registering federation query handler for %r", query_type)
  743. self.query_handlers[query_type] = handler
  744. def register_instance_for_edu(self, edu_type: str, instance_name: str) -> None:
  745. """Register that the EDU handler is on a different instance than master."""
  746. self._edu_type_to_instance[edu_type] = [instance_name]
  747. def register_instances_for_edu(
  748. self, edu_type: str, instance_names: List[str]
  749. ) -> None:
  750. """Register that the EDU handler is on multiple instances."""
  751. self._edu_type_to_instance[edu_type] = instance_names
  752. async def on_edu(self, edu_type: str, origin: str, content: dict) -> None:
  753. if not self.config.use_presence and edu_type == EduTypes.Presence:
  754. return
  755. # If the incoming room key requests from a particular origin are over
  756. # the limit, drop them.
  757. if (
  758. edu_type == EduTypes.RoomKeyRequest
  759. and not await self._room_key_request_rate_limiter.can_do_action(
  760. None, origin
  761. )
  762. ):
  763. return
  764. # Check if we have a handler on this instance
  765. handler = self.edu_handlers.get(edu_type)
  766. if handler:
  767. with start_active_span_from_edu(content, "handle_edu"):
  768. try:
  769. await handler(origin, content)
  770. except SynapseError as e:
  771. logger.info("Failed to handle edu %r: %r", edu_type, e)
  772. except Exception:
  773. logger.exception("Failed to handle edu %r", edu_type)
  774. return
  775. # Check if we can route it somewhere else that isn't us
  776. instances = self._edu_type_to_instance.get(edu_type, ["master"])
  777. if self._instance_name not in instances:
  778. # Pick an instance randomly so that we don't overload one.
  779. route_to = random.choice(instances)
  780. try:
  781. await self._send_edu(
  782. instance_name=route_to,
  783. edu_type=edu_type,
  784. origin=origin,
  785. content=content,
  786. )
  787. except SynapseError as e:
  788. logger.info("Failed to handle edu %r: %r", edu_type, e)
  789. except Exception:
  790. logger.exception("Failed to handle edu %r", edu_type)
  791. return
  792. # Oh well, let's just log and move on.
  793. logger.warning("No handler registered for EDU type %s", edu_type)
  794. async def on_query(self, query_type: str, args: dict) -> JsonDict:
  795. handler = self.query_handlers.get(query_type)
  796. if handler:
  797. return await handler(args)
  798. # Check if we can route it somewhere else that isn't us
  799. if self._instance_name == "master":
  800. return await self._get_query_client(query_type=query_type, args=args)
  801. # Uh oh, no handler! Let's raise an exception so the request returns an
  802. # error.
  803. logger.warning("No handler registered for query type %s", query_type)
  804. raise NotFoundError("No handler for Query type '%s'" % (query_type,))