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.
 
 
 
 
 
 

1402 lines
54 KiB

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