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.
 
 
 
 
 
 

1744 lines
62 KiB

  1. # Copyright 2015-2022 The Matrix.org Foundation C.I.C.
  2. # Copyright 2020 Sorunome
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import copy
  16. import itertools
  17. import logging
  18. from typing import (
  19. TYPE_CHECKING,
  20. Awaitable,
  21. Callable,
  22. Collection,
  23. Container,
  24. Dict,
  25. Iterable,
  26. List,
  27. Mapping,
  28. Optional,
  29. Sequence,
  30. Tuple,
  31. TypeVar,
  32. Union,
  33. )
  34. import attr
  35. from prometheus_client import Counter
  36. from synapse.api.constants import EventContentFields, EventTypes, Membership
  37. from synapse.api.errors import (
  38. CodeMessageException,
  39. Codes,
  40. FederationDeniedError,
  41. HttpResponseException,
  42. RequestSendFailed,
  43. SynapseError,
  44. UnsupportedRoomVersionError,
  45. )
  46. from synapse.api.room_versions import (
  47. KNOWN_ROOM_VERSIONS,
  48. EventFormatVersions,
  49. RoomVersion,
  50. RoomVersions,
  51. )
  52. from synapse.events import EventBase, builder, make_event_from_dict
  53. from synapse.federation.federation_base import (
  54. FederationBase,
  55. InvalidEventSignatureError,
  56. event_from_pdu_json,
  57. )
  58. from synapse.federation.transport.client import SendJoinResponse
  59. from synapse.http.types import QueryParams
  60. from synapse.logging.opentracing import SynapseTags, log_kv, set_tag, tag_args, trace
  61. from synapse.types import JsonDict, UserID, get_domain_from_id
  62. from synapse.util.async_helpers import concurrently_execute
  63. from synapse.util.caches.expiringcache import ExpiringCache
  64. from synapse.util.retryutils import NotRetryingDestination
  65. if TYPE_CHECKING:
  66. from synapse.server import HomeServer
  67. logger = logging.getLogger(__name__)
  68. sent_queries_counter = Counter("synapse_federation_client_sent_queries", "", ["type"])
  69. PDU_RETRY_TIME_MS = 1 * 60 * 1000
  70. T = TypeVar("T")
  71. class InvalidResponseError(RuntimeError):
  72. """Helper for _try_destination_list: indicates that the server returned a response
  73. we couldn't parse
  74. """
  75. @attr.s(slots=True, frozen=True, auto_attribs=True)
  76. class SendJoinResult:
  77. # The event to persist.
  78. event: EventBase
  79. # A string giving the server the event was sent to.
  80. origin: str
  81. state: List[EventBase]
  82. auth_chain: List[EventBase]
  83. # True if 'state' elides non-critical membership events
  84. partial_state: bool
  85. # if 'partial_state' is set, a list of the servers in the room (otherwise empty)
  86. servers_in_room: List[str]
  87. class FederationClient(FederationBase):
  88. def __init__(self, hs: "HomeServer"):
  89. super().__init__(hs)
  90. self.pdu_destination_tried: Dict[str, Dict[str, int]] = {}
  91. self._clock.looping_call(self._clear_tried_cache, 60 * 1000)
  92. self.state = hs.get_state_handler()
  93. self.transport_layer = hs.get_federation_transport_client()
  94. self.hostname = hs.hostname
  95. self.signing_key = hs.signing_key
  96. self._get_pdu_cache: ExpiringCache[str, EventBase] = ExpiringCache(
  97. cache_name="get_pdu_cache",
  98. clock=self._clock,
  99. max_len=1000,
  100. expiry_ms=120 * 1000,
  101. reset_expiry_on_get=False,
  102. )
  103. # A cache for fetching the room hierarchy over federation.
  104. #
  105. # Some stale data over federation is OK, but must be refreshed
  106. # periodically since the local server is in the room.
  107. #
  108. # It is a map of (room ID, suggested-only) -> the response of
  109. # get_room_hierarchy.
  110. self._get_room_hierarchy_cache: ExpiringCache[
  111. Tuple[str, bool],
  112. Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]],
  113. ] = ExpiringCache(
  114. cache_name="get_room_hierarchy_cache",
  115. clock=self._clock,
  116. max_len=1000,
  117. expiry_ms=5 * 60 * 1000,
  118. reset_expiry_on_get=False,
  119. )
  120. def _clear_tried_cache(self) -> None:
  121. """Clear pdu_destination_tried cache"""
  122. now = self._clock.time_msec()
  123. old_dict = self.pdu_destination_tried
  124. self.pdu_destination_tried = {}
  125. for event_id, destination_dict in old_dict.items():
  126. destination_dict = {
  127. dest: time
  128. for dest, time in destination_dict.items()
  129. if time + PDU_RETRY_TIME_MS > now
  130. }
  131. if destination_dict:
  132. self.pdu_destination_tried[event_id] = destination_dict
  133. async def make_query(
  134. self,
  135. destination: str,
  136. query_type: str,
  137. args: QueryParams,
  138. retry_on_dns_fail: bool = False,
  139. ignore_backoff: bool = False,
  140. ) -> JsonDict:
  141. """Sends a federation Query to a remote homeserver of the given type
  142. and arguments.
  143. Args:
  144. destination: Domain name of the remote homeserver
  145. query_type: Category of the query type; should match the
  146. handler name used in register_query_handler().
  147. args: Mapping of strings to strings containing the details
  148. of the query request.
  149. ignore_backoff: true to ignore the historical backoff data
  150. and try the request anyway.
  151. Returns:
  152. The JSON object from the response
  153. """
  154. sent_queries_counter.labels(query_type).inc()
  155. return await self.transport_layer.make_query(
  156. destination,
  157. query_type,
  158. args,
  159. retry_on_dns_fail=retry_on_dns_fail,
  160. ignore_backoff=ignore_backoff,
  161. )
  162. async def query_client_keys(
  163. self, destination: str, content: JsonDict, timeout: int
  164. ) -> JsonDict:
  165. """Query device keys for a device hosted on a remote server.
  166. Args:
  167. destination: Domain name of the remote homeserver
  168. content: The query content.
  169. Returns:
  170. The JSON object from the response
  171. """
  172. sent_queries_counter.labels("client_device_keys").inc()
  173. return await self.transport_layer.query_client_keys(
  174. destination, content, timeout
  175. )
  176. async def query_user_devices(
  177. self, destination: str, user_id: str, timeout: int = 30000
  178. ) -> JsonDict:
  179. """Query the device keys for a list of user ids hosted on a remote
  180. server.
  181. """
  182. sent_queries_counter.labels("user_devices").inc()
  183. return await self.transport_layer.query_user_devices(
  184. destination, user_id, timeout
  185. )
  186. async def claim_client_keys(
  187. self, destination: str, content: JsonDict, timeout: Optional[int]
  188. ) -> JsonDict:
  189. """Claims one-time keys for a device hosted on a remote server.
  190. Args:
  191. destination: Domain name of the remote homeserver
  192. content: The query content.
  193. Returns:
  194. The JSON object from the response
  195. """
  196. sent_queries_counter.labels("client_one_time_keys").inc()
  197. return await self.transport_layer.claim_client_keys(
  198. destination, content, timeout
  199. )
  200. @trace
  201. @tag_args
  202. async def backfill(
  203. self, dest: str, room_id: str, limit: int, extremities: Collection[str]
  204. ) -> Optional[List[EventBase]]:
  205. """Requests some more historic PDUs for the given room from the
  206. given destination server.
  207. Args:
  208. dest: The remote homeserver to ask.
  209. room_id: The room_id to backfill.
  210. limit: The maximum number of events to return.
  211. extremities: our current backwards extremities, to backfill from
  212. Must be a Collection that is falsy when empty.
  213. (Iterable is not enough here!)
  214. """
  215. logger.debug("backfill extrem=%s", extremities)
  216. # If there are no extremities then we've (probably) reached the start.
  217. if not extremities:
  218. return None
  219. transaction_data = await self.transport_layer.backfill(
  220. dest, room_id, extremities, limit
  221. )
  222. logger.debug("backfill transaction_data=%r", transaction_data)
  223. if not isinstance(transaction_data, dict):
  224. # TODO we probably want an exception type specific to federation
  225. # client validation.
  226. raise TypeError("Backfill transaction_data is not a dict.")
  227. transaction_data_pdus = transaction_data.get("pdus")
  228. if not isinstance(transaction_data_pdus, list):
  229. # TODO we probably want an exception type specific to federation
  230. # client validation.
  231. raise TypeError("transaction_data.pdus is not a list.")
  232. room_version = await self.store.get_room_version(room_id)
  233. pdus = [event_from_pdu_json(p, room_version) for p in transaction_data_pdus]
  234. # Check signatures and hash of pdus, removing any from the list that fail checks
  235. pdus[:] = await self._check_sigs_and_hash_and_fetch(
  236. dest, pdus, room_version=room_version
  237. )
  238. return pdus
  239. async def get_pdu_from_destination_raw(
  240. self,
  241. destination: str,
  242. event_id: str,
  243. room_version: RoomVersion,
  244. timeout: Optional[int] = None,
  245. ) -> Optional[EventBase]:
  246. """Requests the PDU with given origin and ID from the remote home
  247. server. Does not have any caching or rate limiting!
  248. Args:
  249. destination: Which homeserver to query
  250. event_id: event to fetch
  251. room_version: version of the room
  252. timeout: How long to try (in ms) each destination for before
  253. moving to the next destination. None indicates no timeout.
  254. Returns:
  255. A copy of the requested PDU that is safe to modify, or None if we
  256. were unable to find it.
  257. Raises:
  258. SynapseError, NotRetryingDestination, FederationDeniedError
  259. """
  260. transaction_data = await self.transport_layer.get_event(
  261. destination, event_id, timeout=timeout
  262. )
  263. logger.debug(
  264. "get_pdu_from_destination_raw: retrieved event id %s from %s: %r",
  265. event_id,
  266. destination,
  267. transaction_data,
  268. )
  269. pdu_list: List[EventBase] = [
  270. event_from_pdu_json(p, room_version) for p in transaction_data["pdus"]
  271. ]
  272. if pdu_list and pdu_list[0]:
  273. pdu = pdu_list[0]
  274. # Check signatures are correct.
  275. try:
  276. signed_pdu = await self._check_sigs_and_hash(room_version, pdu)
  277. except InvalidEventSignatureError as e:
  278. errmsg = f"event id {pdu.event_id}: {e}"
  279. logger.warning("%s", errmsg)
  280. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  281. return signed_pdu
  282. return None
  283. @trace
  284. @tag_args
  285. async def get_pdu(
  286. self,
  287. destinations: Iterable[str],
  288. event_id: str,
  289. room_version: RoomVersion,
  290. timeout: Optional[int] = None,
  291. ) -> Optional[EventBase]:
  292. """Requests the PDU with given origin and ID from the remote home
  293. servers.
  294. Will attempt to get the PDU from each destination in the list until
  295. one succeeds.
  296. Args:
  297. destinations: Which homeservers to query
  298. event_id: event to fetch
  299. room_version: version of the room
  300. timeout: How long to try (in ms) each destination for before
  301. moving to the next destination. None indicates no timeout.
  302. Returns:
  303. The requested PDU, or None if we were unable to find it.
  304. """
  305. logger.debug(
  306. "get_pdu: event_id=%s from destinations=%s", event_id, destinations
  307. )
  308. # TODO: Rate limit the number of times we try and get the same event.
  309. # We might need the same event multiple times in quick succession (before
  310. # it gets persisted to the database), so we cache the results of the lookup.
  311. # Note that this is separate to the regular get_event cache which caches
  312. # events once they have been persisted.
  313. event = self._get_pdu_cache.get(event_id)
  314. # If we don't see the event in the cache, go try to fetch it from the
  315. # provided remote federated destinations
  316. if not event:
  317. pdu_attempts = self.pdu_destination_tried.setdefault(event_id, {})
  318. for destination in destinations:
  319. now = self._clock.time_msec()
  320. last_attempt = pdu_attempts.get(destination, 0)
  321. if last_attempt + PDU_RETRY_TIME_MS > now:
  322. logger.debug(
  323. "get_pdu: skipping destination=%s because we tried it recently last_attempt=%s and we only check every %s (now=%s)",
  324. destination,
  325. last_attempt,
  326. PDU_RETRY_TIME_MS,
  327. now,
  328. )
  329. continue
  330. try:
  331. event = await self.get_pdu_from_destination_raw(
  332. destination=destination,
  333. event_id=event_id,
  334. room_version=room_version,
  335. timeout=timeout,
  336. )
  337. pdu_attempts[destination] = now
  338. if event:
  339. # Prime the cache
  340. self._get_pdu_cache[event.event_id] = event
  341. # Now that we have an event, we can break out of this
  342. # loop and stop asking other destinations.
  343. break
  344. except SynapseError as e:
  345. logger.info(
  346. "Failed to get PDU %s from %s because %s",
  347. event_id,
  348. destination,
  349. e,
  350. )
  351. continue
  352. except NotRetryingDestination as e:
  353. logger.info(str(e))
  354. continue
  355. except FederationDeniedError as e:
  356. logger.info(str(e))
  357. continue
  358. except Exception as e:
  359. pdu_attempts[destination] = now
  360. logger.info(
  361. "Failed to get PDU %s from %s because %s",
  362. event_id,
  363. destination,
  364. e,
  365. )
  366. continue
  367. if not event:
  368. return None
  369. # `event` now refers to an object stored in `get_pdu_cache`. Our
  370. # callers may need to modify the returned object (eg to set
  371. # `event.internal_metadata.outlier = true`), so we return a copy
  372. # rather than the original object.
  373. event_copy = make_event_from_dict(
  374. event.get_pdu_json(),
  375. event.room_version,
  376. )
  377. return event_copy
  378. @trace
  379. @tag_args
  380. async def get_room_state_ids(
  381. self, destination: str, room_id: str, event_id: str
  382. ) -> Tuple[List[str], List[str]]:
  383. """Calls the /state_ids endpoint to fetch the state at a particular point
  384. in the room, and the auth events for the given event
  385. Returns:
  386. a tuple of (state event_ids, auth event_ids)
  387. Raises:
  388. InvalidResponseError: if fields in the response have the wrong type.
  389. """
  390. result = await self.transport_layer.get_room_state_ids(
  391. destination, room_id, event_id=event_id
  392. )
  393. state_event_ids = result["pdu_ids"]
  394. auth_event_ids = result.get("auth_chain_ids", [])
  395. set_tag(
  396. SynapseTags.RESULT_PREFIX + "state_event_ids",
  397. str(state_event_ids),
  398. )
  399. set_tag(
  400. SynapseTags.RESULT_PREFIX + "state_event_ids.length",
  401. str(len(state_event_ids)),
  402. )
  403. set_tag(
  404. SynapseTags.RESULT_PREFIX + "auth_event_ids",
  405. str(auth_event_ids),
  406. )
  407. set_tag(
  408. SynapseTags.RESULT_PREFIX + "auth_event_ids.length",
  409. str(len(auth_event_ids)),
  410. )
  411. if not isinstance(state_event_ids, list) or not isinstance(
  412. auth_event_ids, list
  413. ):
  414. raise InvalidResponseError("invalid response from /state_ids")
  415. return state_event_ids, auth_event_ids
  416. @trace
  417. @tag_args
  418. async def get_room_state(
  419. self,
  420. destination: str,
  421. room_id: str,
  422. event_id: str,
  423. room_version: RoomVersion,
  424. ) -> Tuple[List[EventBase], List[EventBase]]:
  425. """Calls the /state endpoint to fetch the state at a particular point
  426. in the room.
  427. Any invalid events (those with incorrect or unverifiable signatures or hashes)
  428. are filtered out from the response, and any duplicate events are removed.
  429. (Size limits and other event-format checks are *not* performed.)
  430. Note that the result is not ordered, so callers must be careful to process
  431. the events in an order that handles dependencies.
  432. Returns:
  433. a tuple of (state events, auth events)
  434. """
  435. result = await self.transport_layer.get_room_state(
  436. room_version,
  437. destination,
  438. room_id,
  439. event_id,
  440. )
  441. state_events = result.state
  442. auth_events = result.auth_events
  443. # we may as well filter out any duplicates from the response, to save
  444. # processing them multiple times. (In particular, events may be present in
  445. # `auth_events` as well as `state`, which is redundant).
  446. #
  447. # We don't rely on the sort order of the events, so we can just stick them
  448. # in a dict.
  449. state_event_map = {event.event_id: event for event in state_events}
  450. auth_event_map = {
  451. event.event_id: event
  452. for event in auth_events
  453. if event.event_id not in state_event_map
  454. }
  455. logger.info(
  456. "Processing from /state: %d state events, %d auth events",
  457. len(state_event_map),
  458. len(auth_event_map),
  459. )
  460. valid_auth_events = await self._check_sigs_and_hash_and_fetch(
  461. destination, auth_event_map.values(), room_version
  462. )
  463. valid_state_events = await self._check_sigs_and_hash_and_fetch(
  464. destination, state_event_map.values(), room_version
  465. )
  466. return valid_state_events, valid_auth_events
  467. @trace
  468. async def _check_sigs_and_hash_and_fetch(
  469. self,
  470. origin: str,
  471. pdus: Collection[EventBase],
  472. room_version: RoomVersion,
  473. ) -> List[EventBase]:
  474. """Checks the signatures and hashes of a list of events.
  475. If a PDU fails its signature check then we check if we have it in
  476. the database, and if not then request it from the sender's server (if that
  477. is different from `origin`). If that still fails, the event is omitted from
  478. the returned list.
  479. If a PDU fails its content hash check then it is redacted.
  480. Also runs each event through the spam checker; if it fails, redacts the event
  481. and flags it as soft-failed.
  482. The given list of PDUs are not modified; instead the function returns
  483. a new list.
  484. Args:
  485. origin: The server that sent us these events
  486. pdus: The events to be checked
  487. room_version: the version of the room these events are in
  488. Returns:
  489. A list of PDUs that have valid signatures and hashes.
  490. """
  491. set_tag(
  492. SynapseTags.RESULT_PREFIX + "pdus.length",
  493. str(len(pdus)),
  494. )
  495. # We limit how many PDUs we check at once, as if we try to do hundreds
  496. # of thousands of PDUs at once we see large memory spikes.
  497. valid_pdus: List[EventBase] = []
  498. async def _execute(pdu: EventBase) -> None:
  499. valid_pdu = await self._check_sigs_and_hash_and_fetch_one(
  500. pdu=pdu,
  501. origin=origin,
  502. room_version=room_version,
  503. )
  504. if valid_pdu:
  505. valid_pdus.append(valid_pdu)
  506. await concurrently_execute(_execute, pdus, 10000)
  507. return valid_pdus
  508. @trace
  509. @tag_args
  510. async def _check_sigs_and_hash_and_fetch_one(
  511. self,
  512. pdu: EventBase,
  513. origin: str,
  514. room_version: RoomVersion,
  515. ) -> Optional[EventBase]:
  516. """Takes a PDU and checks its signatures and hashes.
  517. If the PDU fails its signature check then we check if we have it in the
  518. database; if not, we then request it from sender's server (if that is not the
  519. same as `origin`). If that still fails, we return None.
  520. If the PDU fails its content hash check, it is redacted.
  521. Also runs the event through the spam checker; if it fails, redacts the event
  522. and flags it as soft-failed.
  523. Args:
  524. origin
  525. pdu
  526. room_version
  527. Returns:
  528. The PDU (possibly redacted) if it has valid signatures and hashes.
  529. None if no valid copy could be found.
  530. """
  531. try:
  532. return await self._check_sigs_and_hash(room_version, pdu)
  533. except InvalidEventSignatureError as e:
  534. logger.warning(
  535. "Signature on retrieved event %s was invalid (%s). "
  536. "Checking local store/origin server",
  537. pdu.event_id,
  538. e,
  539. )
  540. log_kv(
  541. {
  542. "message": "Signature on retrieved event was invalid. "
  543. "Checking local store/origin server",
  544. "event_id": pdu.event_id,
  545. "InvalidEventSignatureError": e,
  546. }
  547. )
  548. # Check local db.
  549. res = await self.store.get_event(
  550. pdu.event_id, allow_rejected=True, allow_none=True
  551. )
  552. # If the PDU fails its signature check and we don't have it in our
  553. # database, we then request it from sender's server (if that is not the
  554. # same as `origin`).
  555. pdu_origin = get_domain_from_id(pdu.sender)
  556. if not res and pdu_origin != origin:
  557. try:
  558. res = await self.get_pdu(
  559. destinations=[pdu_origin],
  560. event_id=pdu.event_id,
  561. room_version=room_version,
  562. timeout=10000,
  563. )
  564. except SynapseError:
  565. pass
  566. if not res:
  567. logger.warning(
  568. "Failed to find copy of %s with valid signature", pdu.event_id
  569. )
  570. return res
  571. async def get_event_auth(
  572. self, destination: str, room_id: str, event_id: str
  573. ) -> List[EventBase]:
  574. res = await self.transport_layer.get_event_auth(destination, room_id, event_id)
  575. room_version = await self.store.get_room_version(room_id)
  576. auth_chain = [event_from_pdu_json(p, room_version) for p in res["auth_chain"]]
  577. signed_auth = await self._check_sigs_and_hash_and_fetch(
  578. destination, auth_chain, room_version=room_version
  579. )
  580. return signed_auth
  581. def _is_unknown_endpoint(
  582. self, e: HttpResponseException, synapse_error: Optional[SynapseError] = None
  583. ) -> bool:
  584. """
  585. Returns true if the response was due to an endpoint being unimplemented.
  586. Args:
  587. e: The error response received from the remote server.
  588. synapse_error: The above error converted to a SynapseError. This is
  589. automatically generated if not provided.
  590. """
  591. if synapse_error is None:
  592. synapse_error = e.to_synapse_error()
  593. # There is no good way to detect an "unknown" endpoint.
  594. #
  595. # Dendrite returns a 404 (with a body of "404 page not found");
  596. # Conduit returns a 404 (with no body); and Synapse returns a 400
  597. # with M_UNRECOGNIZED.
  598. #
  599. # This needs to be rather specific as some endpoints truly do return 404
  600. # errors.
  601. return (
  602. e.code == 404 and (not e.response or e.response == b"404 page not found")
  603. ) or (e.code == 400 and synapse_error.errcode == Codes.UNRECOGNIZED)
  604. async def _try_destination_list(
  605. self,
  606. description: str,
  607. destinations: Iterable[str],
  608. callback: Callable[[str], Awaitable[T]],
  609. failover_errcodes: Optional[Container[str]] = None,
  610. failover_on_unknown_endpoint: bool = False,
  611. ) -> T:
  612. """Try an operation on a series of servers, until it succeeds
  613. Args:
  614. description: description of the operation we're doing, for logging
  615. destinations: list of server_names to try
  616. callback: Function to run for each server. Passed a single
  617. argument: the server_name to try.
  618. If the callback raises a CodeMessageException with a 300/400 code or
  619. an UnsupportedRoomVersionError, attempts to perform the operation
  620. stop immediately and the exception is reraised.
  621. Otherwise, if the callback raises an Exception the error is logged and the
  622. next server tried. Normally the stacktrace is logged but this is
  623. suppressed if the exception is an InvalidResponseError.
  624. failover_errcodes: Error codes (specific to this endpoint) which should
  625. cause a failover when received as part of an HTTP 400 error.
  626. failover_on_unknown_endpoint: if True, we will try other servers if it looks
  627. like a server doesn't support the endpoint. This is typically useful
  628. if the endpoint in question is new or experimental.
  629. Returns:
  630. The result of callback, if it succeeds
  631. Raises:
  632. SynapseError if the chosen remote server returns a 300/400 code, or
  633. no servers were reachable.
  634. """
  635. if failover_errcodes is None:
  636. failover_errcodes = ()
  637. if not destinations:
  638. # Give a bit of a clearer message if no servers were specified at all.
  639. raise SynapseError(
  640. 502, f"Failed to {description} via any server: No servers specified."
  641. )
  642. for destination in destinations:
  643. if destination == self.server_name:
  644. continue
  645. try:
  646. return await callback(destination)
  647. except (
  648. RequestSendFailed,
  649. InvalidResponseError,
  650. NotRetryingDestination,
  651. ) as e:
  652. logger.warning("Failed to %s via %s: %s", description, destination, e)
  653. except UnsupportedRoomVersionError:
  654. raise
  655. except HttpResponseException as e:
  656. synapse_error = e.to_synapse_error()
  657. failover = False
  658. # Failover should occur:
  659. #
  660. # * On internal server errors.
  661. # * If the destination responds that it cannot complete the request.
  662. # * If the destination doesn't implemented the endpoint for some reason.
  663. if 500 <= e.code < 600:
  664. failover = True
  665. elif e.code == 400 and synapse_error.errcode in failover_errcodes:
  666. failover = True
  667. elif failover_on_unknown_endpoint and self._is_unknown_endpoint(
  668. e, synapse_error
  669. ):
  670. failover = True
  671. if not failover:
  672. raise synapse_error from e
  673. logger.warning(
  674. "Failed to %s via %s: %i %s",
  675. description,
  676. destination,
  677. e.code,
  678. e.args[0],
  679. )
  680. except Exception:
  681. logger.warning(
  682. "Failed to %s via %s", description, destination, exc_info=True
  683. )
  684. raise SynapseError(502, f"Failed to {description} via any server")
  685. async def make_membership_event(
  686. self,
  687. destinations: Iterable[str],
  688. room_id: str,
  689. user_id: str,
  690. membership: str,
  691. content: dict,
  692. params: Optional[Mapping[str, Union[str, Iterable[str]]]],
  693. ) -> Tuple[str, EventBase, RoomVersion]:
  694. """
  695. Creates an m.room.member event, with context, without participating in the room.
  696. Does so by asking one of the already participating servers to create an
  697. event with proper context.
  698. Returns a fully signed and hashed event.
  699. Note that this does not append any events to any graphs.
  700. Args:
  701. destinations: Candidate homeservers which are probably
  702. participating in the room.
  703. room_id: The room in which the event will happen.
  704. user_id: The user whose membership is being evented.
  705. membership: The "membership" property of the event. Must be one of
  706. "join" or "leave".
  707. content: Any additional data to put into the content field of the
  708. event.
  709. params: Query parameters to include in the request.
  710. Returns:
  711. `(origin, event, room_version)` where origin is the remote
  712. homeserver which generated the event, and room_version is the
  713. version of the room.
  714. Raises:
  715. UnsupportedRoomVersionError: if remote responds with
  716. a room version we don't understand.
  717. SynapseError: if the chosen remote server returns a 300/400 code, or
  718. no servers successfully handle the request.
  719. """
  720. valid_memberships = {Membership.JOIN, Membership.LEAVE, Membership.KNOCK}
  721. if membership not in valid_memberships:
  722. raise RuntimeError(
  723. "make_membership_event called with membership='%s', must be one of %s"
  724. % (membership, ",".join(valid_memberships))
  725. )
  726. async def send_request(destination: str) -> Tuple[str, EventBase, RoomVersion]:
  727. ret = await self.transport_layer.make_membership_event(
  728. destination, room_id, user_id, membership, params
  729. )
  730. # Note: If not supplied, the room version may be either v1 or v2,
  731. # however either way the event format version will be v1.
  732. room_version_id = ret.get("room_version", RoomVersions.V1.identifier)
  733. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  734. if not room_version:
  735. raise UnsupportedRoomVersionError()
  736. if not room_version.msc2403_knocking and membership == Membership.KNOCK:
  737. raise SynapseError(
  738. 400,
  739. "This room version does not support knocking",
  740. errcode=Codes.FORBIDDEN,
  741. )
  742. pdu_dict = ret.get("event", None)
  743. if not isinstance(pdu_dict, dict):
  744. raise InvalidResponseError("Bad 'event' field in response")
  745. logger.debug("Got response to make_%s: %s", membership, pdu_dict)
  746. pdu_dict["content"].update(content)
  747. # The protoevent received over the JSON wire may not have all
  748. # the required fields. Lets just gloss over that because
  749. # there's some we never care about
  750. ev = builder.create_local_event_from_event_dict(
  751. self._clock,
  752. self.hostname,
  753. self.signing_key,
  754. room_version=room_version,
  755. event_dict=pdu_dict,
  756. )
  757. return destination, ev, room_version
  758. # MSC3083 defines additional error codes for room joins. Unfortunately
  759. # we do not yet know the room version, assume these will only be returned
  760. # by valid room versions.
  761. failover_errcodes = (
  762. (Codes.UNABLE_AUTHORISE_JOIN, Codes.UNABLE_TO_GRANT_JOIN)
  763. if membership == Membership.JOIN
  764. else None
  765. )
  766. return await self._try_destination_list(
  767. "make_" + membership,
  768. destinations,
  769. send_request,
  770. failover_errcodes=failover_errcodes,
  771. )
  772. async def send_join(
  773. self, destinations: Iterable[str], pdu: EventBase, room_version: RoomVersion
  774. ) -> SendJoinResult:
  775. """Sends a join event to one of a list of homeservers.
  776. Doing so will cause the remote server to add the event to the graph,
  777. and send the event out to the rest of the federation.
  778. Args:
  779. destinations: Candidate homeservers which are probably
  780. participating in the room.
  781. pdu: event to be sent
  782. room_version: the version of the room (according to the server that
  783. did the make_join)
  784. Returns:
  785. The result of the send join request.
  786. Raises:
  787. SynapseError: if the chosen remote server returns a 300/400 code, or
  788. no servers successfully handle the request.
  789. """
  790. async def send_request(destination: str) -> SendJoinResult:
  791. response = await self._do_send_join(room_version, destination, pdu)
  792. # If an event was returned (and expected to be returned):
  793. #
  794. # * Ensure it has the same event ID (note that the event ID is a hash
  795. # of the event fields for versions which support MSC3083).
  796. # * Ensure the signatures are good.
  797. #
  798. # Otherwise, fallback to the provided event.
  799. if room_version.msc3083_join_rules and response.event:
  800. event = response.event
  801. valid_pdu = await self._check_sigs_and_hash_and_fetch_one(
  802. pdu=event,
  803. origin=destination,
  804. room_version=room_version,
  805. )
  806. if valid_pdu is None or event.event_id != pdu.event_id:
  807. raise InvalidResponseError("Returned an invalid join event")
  808. else:
  809. event = pdu
  810. state = response.state
  811. auth_chain = response.auth_events
  812. create_event = None
  813. for e in state:
  814. if (e.type, e.state_key) == (EventTypes.Create, ""):
  815. create_event = e
  816. break
  817. if create_event is None:
  818. # If the state doesn't have a create event then the room is
  819. # invalid, and it would fail auth checks anyway.
  820. raise InvalidResponseError("No create event in state")
  821. # the room version should be sane.
  822. create_room_version = create_event.content.get(
  823. "room_version", RoomVersions.V1.identifier
  824. )
  825. if create_room_version != room_version.identifier:
  826. # either the server that fulfilled the make_join, or the server that is
  827. # handling the send_join, is lying.
  828. raise InvalidResponseError(
  829. "Unexpected room version %s in create event"
  830. % (create_room_version,)
  831. )
  832. logger.info(
  833. "Processing from send_join %d events", len(state) + len(auth_chain)
  834. )
  835. # We now go and check the signatures and hashes for the event. Note
  836. # that we limit how many events we process at a time to keep the
  837. # memory overhead from exploding.
  838. valid_pdus_map: Dict[str, EventBase] = {}
  839. async def _execute(pdu: EventBase) -> None:
  840. valid_pdu = await self._check_sigs_and_hash_and_fetch_one(
  841. pdu=pdu,
  842. origin=destination,
  843. room_version=room_version,
  844. )
  845. if valid_pdu:
  846. valid_pdus_map[valid_pdu.event_id] = valid_pdu
  847. await concurrently_execute(
  848. _execute, itertools.chain(state, auth_chain), 10000
  849. )
  850. # NB: We *need* to copy to ensure that we don't have multiple
  851. # references being passed on, as that causes... issues.
  852. signed_state = [
  853. copy.copy(valid_pdus_map[p.event_id])
  854. for p in state
  855. if p.event_id in valid_pdus_map
  856. ]
  857. signed_auth = [
  858. valid_pdus_map[p.event_id]
  859. for p in auth_chain
  860. if p.event_id in valid_pdus_map
  861. ]
  862. # NB: We *need* to copy to ensure that we don't have multiple
  863. # references being passed on, as that causes... issues.
  864. for s in signed_state:
  865. s.internal_metadata = copy.deepcopy(s.internal_metadata)
  866. # double-check that the auth chain doesn't include a different create event
  867. auth_chain_create_events = [
  868. e.event_id
  869. for e in signed_auth
  870. if (e.type, e.state_key) == (EventTypes.Create, "")
  871. ]
  872. if auth_chain_create_events and auth_chain_create_events != [
  873. create_event.event_id
  874. ]:
  875. raise InvalidResponseError(
  876. "Unexpected create event(s) in auth chain: %s"
  877. % (auth_chain_create_events,)
  878. )
  879. if response.partial_state and not response.servers_in_room:
  880. raise InvalidResponseError(
  881. "partial_state was set, but no servers were listed in the room"
  882. )
  883. return SendJoinResult(
  884. event=event,
  885. state=signed_state,
  886. auth_chain=signed_auth,
  887. origin=destination,
  888. partial_state=response.partial_state,
  889. servers_in_room=response.servers_in_room or [],
  890. )
  891. # MSC3083 defines additional error codes for room joins.
  892. failover_errcodes = None
  893. if room_version.msc3083_join_rules:
  894. failover_errcodes = (
  895. Codes.UNABLE_AUTHORISE_JOIN,
  896. Codes.UNABLE_TO_GRANT_JOIN,
  897. )
  898. # If the join is being authorised via allow rules, we need to send
  899. # the /send_join back to the same server that was originally used
  900. # with /make_join.
  901. if EventContentFields.AUTHORISING_USER in pdu.content:
  902. destinations = [
  903. get_domain_from_id(pdu.content[EventContentFields.AUTHORISING_USER])
  904. ]
  905. return await self._try_destination_list(
  906. "send_join", destinations, send_request, failover_errcodes=failover_errcodes
  907. )
  908. async def _do_send_join(
  909. self, room_version: RoomVersion, destination: str, pdu: EventBase
  910. ) -> SendJoinResponse:
  911. time_now = self._clock.time_msec()
  912. try:
  913. return await self.transport_layer.send_join_v2(
  914. room_version=room_version,
  915. destination=destination,
  916. room_id=pdu.room_id,
  917. event_id=pdu.event_id,
  918. content=pdu.get_pdu_json(time_now),
  919. )
  920. except HttpResponseException as e:
  921. # If an error is received that is due to an unrecognised endpoint,
  922. # fallback to the v1 endpoint. Otherwise, consider it a legitimate error
  923. # and raise.
  924. if not self._is_unknown_endpoint(e):
  925. raise
  926. logger.debug("Couldn't send_join with the v2 API, falling back to the v1 API")
  927. return await self.transport_layer.send_join_v1(
  928. room_version=room_version,
  929. destination=destination,
  930. room_id=pdu.room_id,
  931. event_id=pdu.event_id,
  932. content=pdu.get_pdu_json(time_now),
  933. )
  934. async def send_invite(
  935. self,
  936. destination: str,
  937. room_id: str,
  938. event_id: str,
  939. pdu: EventBase,
  940. ) -> EventBase:
  941. room_version = await self.store.get_room_version(room_id)
  942. content = await self._do_send_invite(destination, pdu, room_version)
  943. pdu_dict = content["event"]
  944. logger.debug("Got response to send_invite: %s", pdu_dict)
  945. pdu = event_from_pdu_json(pdu_dict, room_version)
  946. # Check signatures are correct.
  947. try:
  948. pdu = await self._check_sigs_and_hash(room_version, pdu)
  949. except InvalidEventSignatureError as e:
  950. errmsg = f"event id {pdu.event_id}: {e}"
  951. logger.warning("%s", errmsg)
  952. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  953. # FIXME: We should handle signature failures more gracefully.
  954. return pdu
  955. async def _do_send_invite(
  956. self, destination: str, pdu: EventBase, room_version: RoomVersion
  957. ) -> JsonDict:
  958. """Actually sends the invite, first trying v2 API and falling back to
  959. v1 API if necessary.
  960. Returns:
  961. The event as a dict as returned by the remote server
  962. Raises:
  963. SynapseError: if the remote server returns an error or if the server
  964. only supports the v1 endpoint and a room version other than "1"
  965. or "2" is requested.
  966. """
  967. time_now = self._clock.time_msec()
  968. try:
  969. return await self.transport_layer.send_invite_v2(
  970. destination=destination,
  971. room_id=pdu.room_id,
  972. event_id=pdu.event_id,
  973. content={
  974. "event": pdu.get_pdu_json(time_now),
  975. "room_version": room_version.identifier,
  976. "invite_room_state": pdu.unsigned.get("invite_room_state", []),
  977. },
  978. )
  979. except HttpResponseException as e:
  980. # If an error is received that is due to an unrecognised endpoint,
  981. # fallback to the v1 endpoint if the room uses old-style event IDs.
  982. # Otherwise, consider it a legitimate error and raise.
  983. err = e.to_synapse_error()
  984. if self._is_unknown_endpoint(e, err):
  985. if room_version.event_format != EventFormatVersions.ROOM_V1_V2:
  986. raise SynapseError(
  987. 400,
  988. "User's homeserver does not support this room version",
  989. Codes.UNSUPPORTED_ROOM_VERSION,
  990. )
  991. else:
  992. raise err
  993. # Didn't work, try v1 API.
  994. # Note the v1 API returns a tuple of `(200, content)`
  995. _, content = await self.transport_layer.send_invite_v1(
  996. destination=destination,
  997. room_id=pdu.room_id,
  998. event_id=pdu.event_id,
  999. content=pdu.get_pdu_json(time_now),
  1000. )
  1001. return content
  1002. async def send_leave(self, destinations: Iterable[str], pdu: EventBase) -> None:
  1003. """Sends a leave event to one of a list of homeservers.
  1004. Doing so will cause the remote server to add the event to the graph,
  1005. and send the event out to the rest of the federation.
  1006. This is mostly useful to reject received invites.
  1007. Args:
  1008. destinations: Candidate homeservers which are probably
  1009. participating in the room.
  1010. pdu: event to be sent
  1011. Raises:
  1012. SynapseError: if the chosen remote server returns a 300/400 code, or
  1013. no servers successfully handle the request.
  1014. """
  1015. async def send_request(destination: str) -> None:
  1016. content = await self._do_send_leave(destination, pdu)
  1017. logger.debug("Got content: %s", content)
  1018. return await self._try_destination_list(
  1019. "send_leave", destinations, send_request
  1020. )
  1021. async def _do_send_leave(self, destination: str, pdu: EventBase) -> JsonDict:
  1022. time_now = self._clock.time_msec()
  1023. try:
  1024. return await self.transport_layer.send_leave_v2(
  1025. destination=destination,
  1026. room_id=pdu.room_id,
  1027. event_id=pdu.event_id,
  1028. content=pdu.get_pdu_json(time_now),
  1029. )
  1030. except HttpResponseException as e:
  1031. # If an error is received that is due to an unrecognised endpoint,
  1032. # fallback to the v1 endpoint. Otherwise, consider it a legitimate error
  1033. # and raise.
  1034. if not self._is_unknown_endpoint(e):
  1035. raise
  1036. logger.debug("Couldn't send_leave with the v2 API, falling back to the v1 API")
  1037. resp = await self.transport_layer.send_leave_v1(
  1038. destination=destination,
  1039. room_id=pdu.room_id,
  1040. event_id=pdu.event_id,
  1041. content=pdu.get_pdu_json(time_now),
  1042. )
  1043. # We expect the v1 API to respond with [200, content], so we only return the
  1044. # content.
  1045. return resp[1]
  1046. async def send_knock(self, destinations: List[str], pdu: EventBase) -> JsonDict:
  1047. """Attempts to send a knock event to given a list of servers. Iterates
  1048. through the list until one attempt succeeds.
  1049. Doing so will cause the remote server to add the event to the graph,
  1050. and send the event out to the rest of the federation.
  1051. Args:
  1052. destinations: A list of candidate homeservers which are likely to be
  1053. participating in the room.
  1054. pdu: The event to be sent.
  1055. Returns:
  1056. The remote homeserver return some state from the room. The response
  1057. dictionary is in the form:
  1058. {"knock_state_events": [<state event dict>, ...]}
  1059. The list of state events may be empty.
  1060. Raises:
  1061. SynapseError: If the chosen remote server returns a 3xx/4xx code.
  1062. RuntimeError: If no servers were reachable.
  1063. """
  1064. async def send_request(destination: str) -> JsonDict:
  1065. return await self._do_send_knock(destination, pdu)
  1066. return await self._try_destination_list(
  1067. "send_knock", destinations, send_request
  1068. )
  1069. async def _do_send_knock(self, destination: str, pdu: EventBase) -> JsonDict:
  1070. """Send a knock event to a remote homeserver.
  1071. Args:
  1072. destination: The homeserver to send to.
  1073. pdu: The event to send.
  1074. Returns:
  1075. The remote homeserver can optionally return some state from the room. The response
  1076. dictionary is in the form:
  1077. {"knock_state_events": [<state event dict>, ...]}
  1078. The list of state events may be empty.
  1079. """
  1080. time_now = self._clock.time_msec()
  1081. return await self.transport_layer.send_knock_v1(
  1082. destination=destination,
  1083. room_id=pdu.room_id,
  1084. event_id=pdu.event_id,
  1085. content=pdu.get_pdu_json(time_now),
  1086. )
  1087. async def get_public_rooms(
  1088. self,
  1089. remote_server: str,
  1090. limit: Optional[int] = None,
  1091. since_token: Optional[str] = None,
  1092. search_filter: Optional[Dict] = None,
  1093. include_all_networks: bool = False,
  1094. third_party_instance_id: Optional[str] = None,
  1095. ) -> JsonDict:
  1096. """Get the list of public rooms from a remote homeserver
  1097. Args:
  1098. remote_server: The name of the remote server
  1099. limit: Maximum amount of rooms to return
  1100. since_token: Used for result pagination
  1101. search_filter: A filter dictionary to send the remote homeserver
  1102. and filter the result set
  1103. include_all_networks: Whether to include results from all third party instances
  1104. third_party_instance_id: Whether to only include results from a specific third
  1105. party instance
  1106. Returns:
  1107. The response from the remote server.
  1108. Raises:
  1109. HttpResponseException / RequestSendFailed: There was an exception
  1110. returned from the remote server
  1111. SynapseException: M_FORBIDDEN when the remote server has disallowed publicRoom
  1112. requests over federation
  1113. """
  1114. return await self.transport_layer.get_public_rooms(
  1115. remote_server,
  1116. limit,
  1117. since_token,
  1118. search_filter,
  1119. include_all_networks=include_all_networks,
  1120. third_party_instance_id=third_party_instance_id,
  1121. )
  1122. async def get_missing_events(
  1123. self,
  1124. destination: str,
  1125. room_id: str,
  1126. earliest_events_ids: Iterable[str],
  1127. latest_events: Iterable[EventBase],
  1128. limit: int,
  1129. min_depth: int,
  1130. timeout: int,
  1131. ) -> List[EventBase]:
  1132. """Tries to fetch events we are missing. This is called when we receive
  1133. an event without having received all of its ancestors.
  1134. Args:
  1135. destination
  1136. room_id
  1137. earliest_events_ids: List of event ids. Effectively the
  1138. events we expected to receive, but haven't. `get_missing_events`
  1139. should only return events that didn't happen before these.
  1140. latest_events: List of events we have received that we don't
  1141. have all previous events for.
  1142. limit: Maximum number of events to return.
  1143. min_depth: Minimum depth of events to return.
  1144. timeout: Max time to wait in ms
  1145. """
  1146. try:
  1147. content = await self.transport_layer.get_missing_events(
  1148. destination=destination,
  1149. room_id=room_id,
  1150. earliest_events=earliest_events_ids,
  1151. latest_events=[e.event_id for e in latest_events],
  1152. limit=limit,
  1153. min_depth=min_depth,
  1154. timeout=timeout,
  1155. )
  1156. room_version = await self.store.get_room_version(room_id)
  1157. events = [
  1158. event_from_pdu_json(e, room_version) for e in content.get("events", [])
  1159. ]
  1160. signed_events = await self._check_sigs_and_hash_and_fetch(
  1161. destination, events, room_version=room_version
  1162. )
  1163. except HttpResponseException as e:
  1164. if not e.code == 400:
  1165. raise
  1166. # We are probably hitting an old server that doesn't support
  1167. # get_missing_events
  1168. signed_events = []
  1169. return signed_events
  1170. async def forward_third_party_invite(
  1171. self, destinations: Iterable[str], room_id: str, event_dict: JsonDict
  1172. ) -> None:
  1173. for destination in destinations:
  1174. if destination == self.server_name:
  1175. continue
  1176. try:
  1177. await self.transport_layer.exchange_third_party_invite(
  1178. destination=destination, room_id=room_id, event_dict=event_dict
  1179. )
  1180. return
  1181. except CodeMessageException:
  1182. raise
  1183. except Exception as e:
  1184. logger.exception(
  1185. "Failed to send_third_party_invite via %s: %s", destination, str(e)
  1186. )
  1187. raise RuntimeError("Failed to send to any server.")
  1188. async def get_room_complexity(
  1189. self, destination: str, room_id: str
  1190. ) -> Optional[JsonDict]:
  1191. """
  1192. Fetch the complexity of a remote room from another server.
  1193. Args:
  1194. destination: The remote server
  1195. room_id: The room ID to ask about.
  1196. Returns:
  1197. Dict contains the complexity metric versions, while None means we
  1198. could not fetch the complexity.
  1199. """
  1200. try:
  1201. return await self.transport_layer.get_room_complexity(
  1202. destination=destination, room_id=room_id
  1203. )
  1204. except CodeMessageException as e:
  1205. # We didn't manage to get it -- probably a 404. We are okay if other
  1206. # servers don't give it to us.
  1207. logger.debug(
  1208. "Failed to fetch room complexity via %s for %s, got a %d",
  1209. destination,
  1210. room_id,
  1211. e.code,
  1212. )
  1213. except Exception:
  1214. logger.exception(
  1215. "Failed to fetch room complexity via %s for %s", destination, room_id
  1216. )
  1217. # If we don't manage to find it, return None. It's not an error if a
  1218. # server doesn't give it to us.
  1219. return None
  1220. async def get_room_hierarchy(
  1221. self,
  1222. destinations: Iterable[str],
  1223. room_id: str,
  1224. suggested_only: bool,
  1225. ) -> Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]]:
  1226. """
  1227. Call other servers to get a hierarchy of the given room.
  1228. Performs simple data validates and parsing of the response.
  1229. Args:
  1230. destinations: The remote servers. We will try them in turn, omitting any
  1231. that have been blacklisted.
  1232. room_id: ID of the space to be queried
  1233. suggested_only: If true, ask the remote server to only return children
  1234. with the "suggested" flag set
  1235. Returns:
  1236. A tuple of:
  1237. The room as a JSON dictionary, without a "children_state" key.
  1238. A list of `m.space.child` state events.
  1239. A list of children rooms, as JSON dictionaries.
  1240. A list of inaccessible children room IDs.
  1241. Raises:
  1242. SynapseError if we were unable to get a valid summary from any of the
  1243. remote servers
  1244. """
  1245. cached_result = self._get_room_hierarchy_cache.get((room_id, suggested_only))
  1246. if cached_result:
  1247. return cached_result
  1248. async def send_request(
  1249. destination: str,
  1250. ) -> Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]]:
  1251. try:
  1252. res = await self.transport_layer.get_room_hierarchy(
  1253. destination=destination,
  1254. room_id=room_id,
  1255. suggested_only=suggested_only,
  1256. )
  1257. except HttpResponseException as e:
  1258. # If an error is received that is due to an unrecognised endpoint,
  1259. # fallback to the unstable endpoint. Otherwise, consider it a
  1260. # legitimate error and raise.
  1261. if not self._is_unknown_endpoint(e):
  1262. raise
  1263. logger.debug(
  1264. "Couldn't fetch room hierarchy with the v1 API, falling back to the unstable API"
  1265. )
  1266. res = await self.transport_layer.get_room_hierarchy_unstable(
  1267. destination=destination,
  1268. room_id=room_id,
  1269. suggested_only=suggested_only,
  1270. )
  1271. room = res.get("room")
  1272. if not isinstance(room, dict):
  1273. raise InvalidResponseError("'room' must be a dict")
  1274. if room.get("room_id") != room_id:
  1275. raise InvalidResponseError("wrong room returned in hierarchy response")
  1276. # Validate children_state of the room.
  1277. children_state = room.pop("children_state", [])
  1278. if not isinstance(children_state, list):
  1279. raise InvalidResponseError("'room.children_state' must be a list")
  1280. if any(not isinstance(e, dict) for e in children_state):
  1281. raise InvalidResponseError("Invalid event in 'children_state' list")
  1282. try:
  1283. for child_state in children_state:
  1284. _validate_hierarchy_event(child_state)
  1285. except ValueError as e:
  1286. raise InvalidResponseError(str(e))
  1287. # Validate the children rooms.
  1288. children = res.get("children", [])
  1289. if not isinstance(children, list):
  1290. raise InvalidResponseError("'children' must be a list")
  1291. if any(not isinstance(r, dict) for r in children):
  1292. raise InvalidResponseError("Invalid room in 'children' list")
  1293. # Validate the inaccessible children.
  1294. inaccessible_children = res.get("inaccessible_children", [])
  1295. if not isinstance(inaccessible_children, list):
  1296. raise InvalidResponseError("'inaccessible_children' must be a list")
  1297. if any(not isinstance(r, str) for r in inaccessible_children):
  1298. raise InvalidResponseError(
  1299. "Invalid room ID in 'inaccessible_children' list"
  1300. )
  1301. return room, children_state, children, inaccessible_children
  1302. result = await self._try_destination_list(
  1303. "fetch room hierarchy",
  1304. destinations,
  1305. send_request,
  1306. failover_on_unknown_endpoint=True,
  1307. )
  1308. # Cache the result to avoid fetching data over federation every time.
  1309. self._get_room_hierarchy_cache[(room_id, suggested_only)] = result
  1310. return result
  1311. async def timestamp_to_event(
  1312. self, destination: str, room_id: str, timestamp: int, direction: str
  1313. ) -> "TimestampToEventResponse":
  1314. """
  1315. Calls a remote federating server at `destination` asking for their
  1316. closest event to the given timestamp in the given direction. Also
  1317. validates the response to always return the expected keys or raises an
  1318. error.
  1319. Args:
  1320. destination: Domain name of the remote homeserver
  1321. room_id: Room to fetch the event from
  1322. timestamp: The point in time (inclusive) we should navigate from in
  1323. the given direction to find the closest event.
  1324. direction: ["f"|"b"] to indicate whether we should navigate forward
  1325. or backward from the given timestamp to find the closest event.
  1326. Returns:
  1327. A parsed TimestampToEventResponse including the closest event_id
  1328. and origin_server_ts
  1329. Raises:
  1330. Various exceptions when the request fails
  1331. InvalidResponseError when the response does not have the correct
  1332. keys or wrong types
  1333. """
  1334. remote_response = await self.transport_layer.timestamp_to_event(
  1335. destination, room_id, timestamp, direction
  1336. )
  1337. if not isinstance(remote_response, dict):
  1338. raise InvalidResponseError(
  1339. "Response must be a JSON dictionary but received %r" % remote_response
  1340. )
  1341. try:
  1342. return TimestampToEventResponse.from_json_dict(remote_response)
  1343. except ValueError as e:
  1344. raise InvalidResponseError(str(e))
  1345. async def get_account_status(
  1346. self, destination: str, user_ids: List[str]
  1347. ) -> Tuple[JsonDict, List[str]]:
  1348. """Retrieves account statuses for a given list of users on a given remote
  1349. homeserver.
  1350. If the request fails for any reason, all user IDs for this destination are marked
  1351. as failed.
  1352. Args:
  1353. destination: the destination to contact
  1354. user_ids: the user ID(s) for which to request account status(es)
  1355. Returns:
  1356. The account statuses, as well as the list of user IDs for which it was not
  1357. possible to retrieve a status.
  1358. """
  1359. try:
  1360. res = await self.transport_layer.get_account_status(destination, user_ids)
  1361. except Exception:
  1362. # If the query failed for any reason, mark all the users as failed.
  1363. return {}, user_ids
  1364. statuses = res.get("account_statuses", {})
  1365. failures = res.get("failures", [])
  1366. if not isinstance(statuses, dict) or not isinstance(failures, list):
  1367. # Make sure we're not feeding back malformed data back to the caller.
  1368. logger.warning(
  1369. "Destination %s responded with malformed data to account_status query",
  1370. destination,
  1371. )
  1372. return {}, user_ids
  1373. for user_id in user_ids:
  1374. # Any account whose status is missing is a user we failed to receive the
  1375. # status of.
  1376. if user_id not in statuses and user_id not in failures:
  1377. failures.append(user_id)
  1378. # Filter out any user ID that doesn't belong to the remote server that sent its
  1379. # status (or failure).
  1380. def filter_user_id(user_id: str) -> bool:
  1381. try:
  1382. return UserID.from_string(user_id).domain == destination
  1383. except SynapseError:
  1384. # If the user ID doesn't parse, ignore it.
  1385. return False
  1386. filtered_statuses = dict(
  1387. # item is a (key, value) tuple, so item[0] is the user ID.
  1388. filter(lambda item: filter_user_id(item[0]), statuses.items())
  1389. )
  1390. filtered_failures = list(filter(filter_user_id, failures))
  1391. return filtered_statuses, filtered_failures
  1392. @attr.s(frozen=True, slots=True, auto_attribs=True)
  1393. class TimestampToEventResponse:
  1394. """Typed response dictionary for the federation /timestamp_to_event endpoint"""
  1395. event_id: str
  1396. origin_server_ts: int
  1397. # the raw data, including the above keys
  1398. data: JsonDict
  1399. @classmethod
  1400. def from_json_dict(cls, d: JsonDict) -> "TimestampToEventResponse":
  1401. """Parsed response from the federation /timestamp_to_event endpoint
  1402. Args:
  1403. d: JSON object response to be parsed
  1404. Raises:
  1405. ValueError if d does not the correct keys or they are the wrong types
  1406. """
  1407. event_id = d.get("event_id")
  1408. if not isinstance(event_id, str):
  1409. raise ValueError(
  1410. "Invalid response: 'event_id' must be a str but received %r" % event_id
  1411. )
  1412. origin_server_ts = d.get("origin_server_ts")
  1413. if not isinstance(origin_server_ts, int):
  1414. raise ValueError(
  1415. "Invalid response: 'origin_server_ts' must be a int but received %r"
  1416. % origin_server_ts
  1417. )
  1418. return cls(event_id, origin_server_ts, d)
  1419. def _validate_hierarchy_event(d: JsonDict) -> None:
  1420. """Validate an event within the result of a /hierarchy request
  1421. Args:
  1422. d: json object to be parsed
  1423. Raises:
  1424. ValueError if d is not a valid event
  1425. """
  1426. event_type = d.get("type")
  1427. if not isinstance(event_type, str):
  1428. raise ValueError("Invalid event: 'event_type' must be a str")
  1429. state_key = d.get("state_key")
  1430. if not isinstance(state_key, str):
  1431. raise ValueError("Invalid event: 'state_key' must be a str")
  1432. content = d.get("content")
  1433. if not isinstance(content, dict):
  1434. raise ValueError("Invalid event: 'content' must be a dict")
  1435. via = content.get("via")
  1436. if not isinstance(via, list):
  1437. raise ValueError("Invalid event: 'via' must be a list")
  1438. if any(not isinstance(v, str) for v in via):
  1439. raise ValueError("Invalid event: 'via' must be a list of strings")