federation_client.py 63 KB

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