federation_event.py 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import collections
  15. import itertools
  16. import logging
  17. from http import HTTPStatus
  18. from typing import (
  19. TYPE_CHECKING,
  20. Collection,
  21. Container,
  22. Dict,
  23. Iterable,
  24. List,
  25. Optional,
  26. Sequence,
  27. Set,
  28. Tuple,
  29. )
  30. from prometheus_client import Counter, Histogram
  31. from synapse import event_auth
  32. from synapse.api.constants import (
  33. EventContentFields,
  34. EventTypes,
  35. GuestAccess,
  36. Membership,
  37. RejectedReason,
  38. RoomEncryptionAlgorithms,
  39. )
  40. from synapse.api.errors import (
  41. AuthError,
  42. Codes,
  43. EventSizeError,
  44. FederationError,
  45. FederationPullAttemptBackoffError,
  46. HttpResponseException,
  47. RequestSendFailed,
  48. SynapseError,
  49. )
  50. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion, RoomVersions
  51. from synapse.event_auth import (
  52. auth_types_for_event,
  53. check_state_dependent_auth_rules,
  54. check_state_independent_auth_rules,
  55. validate_event_for_room_version,
  56. )
  57. from synapse.events import EventBase
  58. from synapse.events.snapshot import EventContext
  59. from synapse.federation.federation_client import InvalidResponseError, PulledPduInfo
  60. from synapse.logging.context import nested_logging_context
  61. from synapse.logging.opentracing import (
  62. SynapseTags,
  63. set_tag,
  64. start_active_span,
  65. tag_args,
  66. trace,
  67. )
  68. from synapse.metrics.background_process_metrics import run_as_background_process
  69. from synapse.replication.http.devices import ReplicationUserDevicesResyncRestServlet
  70. from synapse.replication.http.federation import (
  71. ReplicationFederationSendEventsRestServlet,
  72. )
  73. from synapse.state import StateResolutionStore
  74. from synapse.storage.databases.main.events import PartialStateConflictError
  75. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  76. from synapse.types import (
  77. PersistedEventPosition,
  78. RoomStreamToken,
  79. StateMap,
  80. UserID,
  81. get_domain_from_id,
  82. )
  83. from synapse.types.state import StateFilter
  84. from synapse.util.async_helpers import Linearizer, concurrently_execute
  85. from synapse.util.iterutils import batch_iter
  86. from synapse.util.retryutils import NotRetryingDestination
  87. from synapse.util.stringutils import shortstr
  88. if TYPE_CHECKING:
  89. from synapse.server import HomeServer
  90. logger = logging.getLogger(__name__)
  91. soft_failed_event_counter = Counter(
  92. "synapse_federation_soft_failed_events_total",
  93. "Events received over federation that we marked as soft_failed",
  94. )
  95. # Added to debug performance and track progress on optimizations
  96. backfill_processing_after_timer = Histogram(
  97. "synapse_federation_backfill_processing_after_time_seconds",
  98. "sec",
  99. [],
  100. buckets=(
  101. 0.1,
  102. 0.25,
  103. 0.5,
  104. 1.0,
  105. 2.5,
  106. 5.0,
  107. 7.5,
  108. 10.0,
  109. 15.0,
  110. 20.0,
  111. 25.0,
  112. 30.0,
  113. 40.0,
  114. 50.0,
  115. 60.0,
  116. 80.0,
  117. 100.0,
  118. 120.0,
  119. 150.0,
  120. 180.0,
  121. "+Inf",
  122. ),
  123. )
  124. class FederationEventHandler:
  125. """Handles events that originated from federation.
  126. Responsible for handing incoming events and passing them on to the rest
  127. of the homeserver (including auth and state conflict resolutions)
  128. """
  129. def __init__(self, hs: "HomeServer"):
  130. self._store = hs.get_datastores().main
  131. self._storage_controllers = hs.get_storage_controllers()
  132. self._state_storage_controller = self._storage_controllers.state
  133. self._state_handler = hs.get_state_handler()
  134. self._event_creation_handler = hs.get_event_creation_handler()
  135. self._event_auth_handler = hs.get_event_auth_handler()
  136. self._message_handler = hs.get_message_handler()
  137. self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()
  138. self._state_resolution_handler = hs.get_state_resolution_handler()
  139. # avoid a circular dependency by deferring execution here
  140. self._get_room_member_handler = hs.get_room_member_handler
  141. self._federation_client = hs.get_federation_client()
  142. self._third_party_event_rules = hs.get_third_party_event_rules()
  143. self._notifier = hs.get_notifier()
  144. self._is_mine_id = hs.is_mine_id
  145. self._server_name = hs.hostname
  146. self._instance_name = hs.get_instance_name()
  147. self._config = hs.config
  148. self._ephemeral_messages_enabled = hs.config.server.enable_ephemeral_messages
  149. self._send_events = ReplicationFederationSendEventsRestServlet.make_client(hs)
  150. if hs.config.worker.worker_app:
  151. self._user_device_resync = (
  152. ReplicationUserDevicesResyncRestServlet.make_client(hs)
  153. )
  154. else:
  155. self._device_list_updater = hs.get_device_handler().device_list_updater
  156. # When joining a room we need to queue any events for that room up.
  157. # For each room, a list of (pdu, origin) tuples.
  158. # TODO: replace this with something more elegant, probably based around the
  159. # federation event staging area.
  160. self.room_queues: Dict[str, List[Tuple[EventBase, str]]] = {}
  161. self._room_pdu_linearizer = Linearizer("fed_room_pdu")
  162. async def on_receive_pdu(self, origin: str, pdu: EventBase) -> None:
  163. """Process a PDU received via a federation /send/ transaction
  164. Args:
  165. origin: server which initiated the /send/ transaction. Will
  166. be used to fetch missing events or state.
  167. pdu: received PDU
  168. """
  169. # We should never see any outliers here.
  170. assert not pdu.internal_metadata.outlier
  171. room_id = pdu.room_id
  172. event_id = pdu.event_id
  173. # We reprocess pdus when we have seen them only as outliers
  174. existing = await self._store.get_event(
  175. event_id, allow_none=True, allow_rejected=True
  176. )
  177. # FIXME: Currently we fetch an event again when we already have it
  178. # if it has been marked as an outlier.
  179. if existing:
  180. if not existing.internal_metadata.is_outlier():
  181. logger.info(
  182. "Ignoring received event %s which we have already seen", event_id
  183. )
  184. return
  185. if pdu.internal_metadata.is_outlier():
  186. logger.info(
  187. "Ignoring received outlier %s which we already have as an outlier",
  188. event_id,
  189. )
  190. return
  191. logger.info("De-outliering event %s", event_id)
  192. # do some initial sanity-checking of the event. In particular, make
  193. # sure it doesn't have hundreds of prev_events or auth_events, which
  194. # could cause a huge state resolution or cascade of event fetches.
  195. try:
  196. self._sanity_check_event(pdu)
  197. except SynapseError as err:
  198. logger.warning("Received event failed sanity checks")
  199. raise FederationError("ERROR", err.code, err.msg, affected=pdu.event_id)
  200. # If we are currently in the process of joining this room, then we
  201. # queue up events for later processing.
  202. if room_id in self.room_queues:
  203. logger.info(
  204. "Queuing PDU from %s for now: join in progress",
  205. origin,
  206. )
  207. self.room_queues[room_id].append((pdu, origin))
  208. return
  209. # If we're not in the room just ditch the event entirely. This is
  210. # probably an old server that has come back and thinks we're still in
  211. # the room (or we've been rejoined to the room by a state reset).
  212. #
  213. # Note that if we were never in the room then we would have already
  214. # dropped the event, since we wouldn't know the room version.
  215. is_in_room = await self._event_auth_handler.is_host_in_room(
  216. room_id, self._server_name
  217. )
  218. if not is_in_room:
  219. logger.info(
  220. "Ignoring PDU from %s as we're not in the room",
  221. origin,
  222. )
  223. return None
  224. # Try to fetch any missing prev events to fill in gaps in the graph
  225. prevs = set(pdu.prev_event_ids())
  226. seen = await self._store.have_events_in_timeline(prevs)
  227. missing_prevs = prevs - seen
  228. if missing_prevs:
  229. # We only backfill backwards to the min depth.
  230. min_depth = await self._store.get_min_depth(pdu.room_id)
  231. logger.debug("min_depth: %d", min_depth)
  232. if min_depth is not None and pdu.depth > min_depth:
  233. # If we're missing stuff, ensure we only fetch stuff one
  234. # at a time.
  235. logger.info(
  236. "Acquiring room lock to fetch %d missing prev_events: %s",
  237. len(missing_prevs),
  238. shortstr(missing_prevs),
  239. )
  240. async with self._room_pdu_linearizer.queue(pdu.room_id):
  241. logger.info(
  242. "Acquired room lock to fetch %d missing prev_events",
  243. len(missing_prevs),
  244. )
  245. try:
  246. await self._get_missing_events_for_pdu(
  247. origin, pdu, prevs, min_depth
  248. )
  249. except Exception as e:
  250. raise Exception(
  251. "Error fetching missing prev_events for %s: %s"
  252. % (event_id, e)
  253. ) from e
  254. # Update the set of things we've seen after trying to
  255. # fetch the missing stuff
  256. seen = await self._store.have_events_in_timeline(prevs)
  257. missing_prevs = prevs - seen
  258. if not missing_prevs:
  259. logger.info("Found all missing prev_events")
  260. if missing_prevs:
  261. # since this event was pushed to us, it is possible for it to
  262. # become the only forward-extremity in the room, and we would then
  263. # trust its state to be the state for the whole room. This is very
  264. # bad. Further, if the event was pushed to us, there is no excuse
  265. # for us not to have all the prev_events. (XXX: apart from
  266. # min_depth?)
  267. #
  268. # We therefore reject any such events.
  269. logger.warning(
  270. "Rejecting: failed to fetch %d prev events: %s",
  271. len(missing_prevs),
  272. shortstr(missing_prevs),
  273. )
  274. raise FederationError(
  275. "ERROR",
  276. 403,
  277. (
  278. "Your server isn't divulging details about prev_events "
  279. "referenced in this event."
  280. ),
  281. affected=pdu.event_id,
  282. )
  283. try:
  284. context = await self._state_handler.compute_event_context(pdu)
  285. await self._process_received_pdu(origin, pdu, context)
  286. except PartialStateConflictError:
  287. # The room was un-partial stated while we were processing the PDU.
  288. # Try once more, with full state this time.
  289. logger.info(
  290. "Room %s was un-partial stated while processing the PDU, trying again.",
  291. room_id,
  292. )
  293. context = await self._state_handler.compute_event_context(pdu)
  294. await self._process_received_pdu(origin, pdu, context)
  295. async def on_send_membership_event(
  296. self, origin: str, event: EventBase
  297. ) -> Tuple[EventBase, EventContext]:
  298. """
  299. We have received a join/leave/knock event for a room via send_join/leave/knock.
  300. Verify that event and send it into the room on the remote homeserver's behalf.
  301. This is quite similar to on_receive_pdu, with the following principal
  302. differences:
  303. * only membership events are permitted (and only events with
  304. sender==state_key -- ie, no kicks or bans)
  305. * *We* send out the event on behalf of the remote server.
  306. * We enforce the membership restrictions of restricted rooms.
  307. * Rejected events result in an exception rather than being stored.
  308. There are also other differences, however it is not clear if these are by
  309. design or omission. In particular, we do not attempt to backfill any missing
  310. prev_events.
  311. Args:
  312. origin: The homeserver of the remote (joining/invited/knocking) user.
  313. event: The member event that has been signed by the remote homeserver.
  314. Returns:
  315. The event and context of the event after inserting it into the room graph.
  316. Raises:
  317. RuntimeError if any prev_events are missing
  318. SynapseError if the event is not accepted into the room
  319. PartialStateConflictError if the room was un-partial stated in between
  320. computing the state at the event and persisting it. The caller should
  321. retry exactly once in this case.
  322. """
  323. logger.debug(
  324. "on_send_membership_event: Got event: %s, signatures: %s",
  325. event.event_id,
  326. event.signatures,
  327. )
  328. if get_domain_from_id(event.sender) != origin:
  329. logger.info(
  330. "Got send_membership request for user %r from different origin %s",
  331. event.sender,
  332. origin,
  333. )
  334. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  335. if event.sender != event.state_key:
  336. raise SynapseError(400, "state_key and sender must match", Codes.BAD_JSON)
  337. assert not event.internal_metadata.outlier
  338. # Send this event on behalf of the other server.
  339. #
  340. # The remote server isn't a full participant in the room at this point, so
  341. # may not have an up-to-date list of the other homeservers participating in
  342. # the room, so we send it on their behalf.
  343. event.internal_metadata.send_on_behalf_of = origin
  344. context = await self._state_handler.compute_event_context(event)
  345. await self._check_event_auth(origin, event, context)
  346. if context.rejected:
  347. raise SynapseError(
  348. 403, f"{event.membership} event was rejected", Codes.FORBIDDEN
  349. )
  350. # for joins, we need to check the restrictions of restricted rooms
  351. if event.membership == Membership.JOIN:
  352. await self.check_join_restrictions(context, event)
  353. # for knock events, we run the third-party event rules. It's not entirely clear
  354. # why we don't do this for other sorts of membership events.
  355. if event.membership == Membership.KNOCK:
  356. event_allowed, _ = await self._third_party_event_rules.check_event_allowed(
  357. event, context
  358. )
  359. if not event_allowed:
  360. logger.info("Sending of knock %s forbidden by third-party rules", event)
  361. raise SynapseError(
  362. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  363. )
  364. # all looks good, we can persist the event.
  365. # First, precalculate the joined hosts so that the federation sender doesn't
  366. # need to.
  367. await self._event_creation_handler.cache_joined_hosts_for_events(
  368. [(event, context)]
  369. )
  370. await self._check_for_soft_fail(event, context=context, origin=origin)
  371. await self._run_push_actions_and_persist_event(event, context)
  372. return event, context
  373. async def check_join_restrictions(
  374. self, context: EventContext, event: EventBase
  375. ) -> None:
  376. """Check that restrictions in restricted join rules are matched
  377. Called when we receive a join event via send_join.
  378. Raises an auth error if the restrictions are not matched.
  379. """
  380. prev_state_ids = await context.get_prev_state_ids()
  381. # Check if the user is already in the room or invited to the room.
  382. user_id = event.state_key
  383. prev_member_event_id = prev_state_ids.get((EventTypes.Member, user_id), None)
  384. prev_member_event = None
  385. if prev_member_event_id:
  386. prev_member_event = await self._store.get_event(prev_member_event_id)
  387. # Check if the member should be allowed access via membership in a space.
  388. await self._event_auth_handler.check_restricted_join_rules(
  389. prev_state_ids,
  390. event.room_version,
  391. user_id,
  392. prev_member_event,
  393. )
  394. @trace
  395. async def process_remote_join(
  396. self,
  397. origin: str,
  398. room_id: str,
  399. auth_events: List[EventBase],
  400. state: List[EventBase],
  401. event: EventBase,
  402. room_version: RoomVersion,
  403. partial_state: bool,
  404. ) -> int:
  405. """Persists the events returned by a send_join
  406. Checks the auth chain is valid (and passes auth checks) for the
  407. state and event. Then persists all of the events.
  408. Notifies about the persisted events where appropriate.
  409. Args:
  410. origin: Where the events came from
  411. room_id:
  412. auth_events
  413. state
  414. event
  415. room_version: The room version we expect this room to have, and
  416. will raise if it doesn't match the version in the create event.
  417. partial_state: True if the state omits non-critical membership events
  418. Returns:
  419. The stream ID after which all events have been persisted.
  420. Raises:
  421. SynapseError if the response is in some way invalid.
  422. PartialStateConflictError if the homeserver is already in the room and it
  423. has been un-partial stated.
  424. """
  425. create_event = None
  426. for e in state:
  427. if (e.type, e.state_key) == (EventTypes.Create, ""):
  428. create_event = e
  429. break
  430. if create_event is None:
  431. # If the state doesn't have a create event then the room is
  432. # invalid, and it would fail auth checks anyway.
  433. raise SynapseError(400, "No create event in state")
  434. room_version_id = create_event.content.get(
  435. "room_version", RoomVersions.V1.identifier
  436. )
  437. if room_version.identifier != room_version_id:
  438. raise SynapseError(400, "Room version mismatch")
  439. # persist the auth chain and state events.
  440. #
  441. # any invalid events here will be marked as rejected, and we'll carry on.
  442. #
  443. # any events whose auth events are missing (ie, not in the send_join response,
  444. # and not already in our db) will just be ignored. This is correct behaviour,
  445. # because the reason that auth_events are missing might be due to us being
  446. # unable to validate their signatures. The fact that we can't validate their
  447. # signatures right now doesn't mean that we will *never* be able to, so it
  448. # is premature to reject them.
  449. #
  450. await self._auth_and_persist_outliers(
  451. room_id, itertools.chain(auth_events, state)
  452. )
  453. # and now persist the join event itself.
  454. logger.info(
  455. "Peristing join-via-remote %s (partial_state: %s)", event, partial_state
  456. )
  457. with nested_logging_context(suffix=event.event_id):
  458. context = await self._state_handler.compute_event_context(
  459. event,
  460. state_ids_before_event={
  461. (e.type, e.state_key): e.event_id for e in state
  462. },
  463. partial_state=partial_state,
  464. )
  465. await self._check_event_auth(origin, event, context)
  466. if context.rejected:
  467. raise SynapseError(400, "Join event was rejected")
  468. # the remote server is responsible for sending our join event to the rest
  469. # of the federation. Indeed, attempting to do so will result in problems
  470. # when we try to look up the state before the join (to get the server list)
  471. # and discover that we do not have it.
  472. event.internal_metadata.proactively_send = False
  473. stream_id_after_persist = await self.persist_events_and_notify(
  474. room_id, [(event, context)]
  475. )
  476. # If we're joining the room again, check if there is new marker
  477. # state indicating that there is new history imported somewhere in
  478. # the DAG. Multiple markers can exist in the current state with
  479. # unique state_keys.
  480. #
  481. # Do this after the state from the remote join was persisted (via
  482. # `persist_events_and_notify`). Otherwise we can run into a
  483. # situation where the create event doesn't exist yet in the
  484. # `current_state_events`
  485. for e in state:
  486. await self._handle_marker_event(origin, e)
  487. return stream_id_after_persist
  488. async def update_state_for_partial_state_event(
  489. self, destination: str, event: EventBase
  490. ) -> None:
  491. """Recalculate the state at an event as part of a de-partial-stating process
  492. Args:
  493. destination: server to request full state from
  494. event: partial-state event to be de-partial-stated
  495. Raises:
  496. FederationPullAttemptBackoffError if we are are deliberately not attempting
  497. to pull the given event over federation because we've already done so
  498. recently and are backing off.
  499. FederationError if we fail to request state from the remote server.
  500. """
  501. logger.info("Updating state for %s", event.event_id)
  502. with nested_logging_context(suffix=event.event_id):
  503. # if we have all the event's prev_events, then we can work out the
  504. # state based on their states. Otherwise, we request it from the destination
  505. # server.
  506. #
  507. # This is the same operation as we do when we receive a regular event
  508. # over federation.
  509. context = await self._compute_event_context_with_maybe_missing_prevs(
  510. destination, event
  511. )
  512. if context.partial_state:
  513. # this can happen if some or all of the event's prev_events still have
  514. # partial state. We were careful to only pick events from the db without
  515. # partial-state prev events, so that implies that a prev event has
  516. # been persisted (with partial state) since we did the query.
  517. #
  518. # So, let's just ignore `event` for now; when we re-run the db query
  519. # we should instead get its partial-state prev event, which we will
  520. # de-partial-state, and then come back to event.
  521. logger.warning(
  522. "%s still has prev_events with partial state: can't de-partial-state it yet",
  523. event.event_id,
  524. )
  525. return
  526. # since the state at this event has changed, we should now re-evaluate
  527. # whether it should have been rejected. We must already have all of the
  528. # auth events (from last time we went round this path), so there is no
  529. # need to pass the origin.
  530. await self._check_event_auth(None, event, context)
  531. await self._store.update_state_for_partial_state_event(event, context)
  532. self._state_storage_controller.notify_event_un_partial_stated(
  533. event.event_id
  534. )
  535. # Notify that there's a new row in the un_partial_stated_events stream.
  536. self._notifier.notify_replication()
  537. @trace
  538. async def backfill(
  539. self, dest: str, room_id: str, limit: int, extremities: Collection[str]
  540. ) -> None:
  541. """Trigger a backfill request to `dest` for the given `room_id`
  542. This will attempt to get more events from the remote. If the other side
  543. has no new events to offer, this will return an empty list.
  544. As the events are received, we check their signatures, and also do some
  545. sanity-checking on them. If any of the backfilled events are invalid,
  546. this method throws a SynapseError.
  547. We might also raise an InvalidResponseError if the response from the remote
  548. server is just bogus.
  549. TODO: make this more useful to distinguish failures of the remote
  550. server from invalid events (there is probably no point in trying to
  551. re-fetch invalid events from every other HS in the room.)
  552. """
  553. if dest == self._server_name:
  554. raise SynapseError(400, "Can't backfill from self.")
  555. events = await self._federation_client.backfill(
  556. dest, room_id, limit=limit, extremities=extremities
  557. )
  558. if not events:
  559. return
  560. with backfill_processing_after_timer.time():
  561. # if there are any events in the wrong room, the remote server is buggy and
  562. # should not be trusted.
  563. for ev in events:
  564. if ev.room_id != room_id:
  565. raise InvalidResponseError(
  566. f"Remote server {dest} returned event {ev.event_id} which is in "
  567. f"room {ev.room_id}, when we were backfilling in {room_id}"
  568. )
  569. await self._process_pulled_events(
  570. dest,
  571. events,
  572. backfilled=True,
  573. )
  574. @trace
  575. async def _get_missing_events_for_pdu(
  576. self, origin: str, pdu: EventBase, prevs: Set[str], min_depth: int
  577. ) -> None:
  578. """
  579. Args:
  580. origin: Origin of the pdu. Will be called to get the missing events
  581. pdu: received pdu
  582. prevs: List of event ids which we are missing
  583. min_depth: Minimum depth of events to return.
  584. """
  585. room_id = pdu.room_id
  586. event_id = pdu.event_id
  587. seen = await self._store.have_events_in_timeline(prevs)
  588. if not prevs - seen:
  589. return
  590. latest_list = await self._store.get_latest_event_ids_in_room(room_id)
  591. # We add the prev events that we have seen to the latest
  592. # list to ensure the remote server doesn't give them to us
  593. latest = set(latest_list)
  594. latest |= seen
  595. logger.info(
  596. "Requesting missing events between %s and %s",
  597. shortstr(latest),
  598. event_id,
  599. )
  600. # XXX: we set timeout to 10s to help workaround
  601. # https://github.com/matrix-org/synapse/issues/1733.
  602. # The reason is to avoid holding the linearizer lock
  603. # whilst processing inbound /send transactions, causing
  604. # FDs to stack up and block other inbound transactions
  605. # which empirically can currently take up to 30 minutes.
  606. #
  607. # N.B. this explicitly disables retry attempts.
  608. #
  609. # N.B. this also increases our chances of falling back to
  610. # fetching fresh state for the room if the missing event
  611. # can't be found, which slightly reduces our security.
  612. # it may also increase our DAG extremity count for the room,
  613. # causing additional state resolution? See #1760.
  614. # However, fetching state doesn't hold the linearizer lock
  615. # apparently.
  616. #
  617. # see https://github.com/matrix-org/synapse/pull/1744
  618. #
  619. # ----
  620. #
  621. # Update richvdh 2018/09/18: There are a number of problems with timing this
  622. # request out aggressively on the client side:
  623. #
  624. # - it plays badly with the server-side rate-limiter, which starts tarpitting you
  625. # if you send too many requests at once, so you end up with the server carefully
  626. # working through the backlog of your requests, which you have already timed
  627. # out.
  628. #
  629. # - for this request in particular, we now (as of
  630. # https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the
  631. # server can't produce a plausible-looking set of prev_events - so we becone
  632. # much more likely to reject the event.
  633. #
  634. # - contrary to what it says above, we do *not* fall back to fetching fresh state
  635. # for the room if get_missing_events times out. Rather, we give up processing
  636. # the PDU whose prevs we are missing, which then makes it much more likely that
  637. # we'll end up back here for the *next* PDU in the list, which exacerbates the
  638. # problem.
  639. #
  640. # - the aggressive 10s timeout was introduced to deal with incoming federation
  641. # requests taking 8 hours to process. It's not entirely clear why that was going
  642. # on; certainly there were other issues causing traffic storms which are now
  643. # resolved, and I think in any case we may be more sensible about our locking
  644. # now. We're *certainly* more sensible about our logging.
  645. #
  646. # All that said: Let's try increasing the timeout to 60s and see what happens.
  647. try:
  648. missing_events = await self._federation_client.get_missing_events(
  649. origin,
  650. room_id,
  651. earliest_events_ids=list(latest),
  652. latest_events=[pdu],
  653. limit=10,
  654. min_depth=min_depth,
  655. timeout=60000,
  656. )
  657. except (RequestSendFailed, HttpResponseException, NotRetryingDestination) as e:
  658. # We failed to get the missing events, but since we need to handle
  659. # the case of `get_missing_events` not returning the necessary
  660. # events anyway, it is safe to simply log the error and continue.
  661. logger.warning("Failed to get prev_events: %s", e)
  662. return
  663. logger.info("Got %d prev_events", len(missing_events))
  664. await self._process_pulled_events(origin, missing_events, backfilled=False)
  665. @trace
  666. async def _process_pulled_events(
  667. self, origin: str, events: Collection[EventBase], backfilled: bool
  668. ) -> None:
  669. """Process a batch of events we have pulled from a remote server
  670. Pulls in any events required to auth the events, persists the received events,
  671. and notifies clients, if appropriate.
  672. Assumes the events have already had their signatures and hashes checked.
  673. Params:
  674. origin: The server we received these events from
  675. events: The received events.
  676. backfilled: True if this is part of a historical batch of events (inhibits
  677. notification to clients, and validation of device keys.)
  678. """
  679. set_tag(
  680. SynapseTags.FUNC_ARG_PREFIX + "event_ids",
  681. str([event.event_id for event in events]),
  682. )
  683. set_tag(
  684. SynapseTags.FUNC_ARG_PREFIX + "event_ids.length",
  685. str(len(events)),
  686. )
  687. set_tag(SynapseTags.FUNC_ARG_PREFIX + "backfilled", str(backfilled))
  688. logger.debug(
  689. "processing pulled backfilled=%s events=%s",
  690. backfilled,
  691. [
  692. "event_id=%s,depth=%d,body=%s,prevs=%s\n"
  693. % (
  694. event.event_id,
  695. event.depth,
  696. event.content.get("body", event.type),
  697. event.prev_event_ids(),
  698. )
  699. for event in events
  700. ],
  701. )
  702. # Check if we already any of these have these events.
  703. # Note: we currently make a lookup in the database directly here rather than
  704. # checking the event cache, due to:
  705. # https://github.com/matrix-org/synapse/issues/13476
  706. existing_events_map = await self._store._get_events_from_db(
  707. [event.event_id for event in events]
  708. )
  709. new_events = []
  710. for event in events:
  711. event_id = event.event_id
  712. # If we've already seen this event ID...
  713. if event_id in existing_events_map:
  714. existing_event = existing_events_map[event_id]
  715. # ...and the event itself was not previously stored as an outlier...
  716. if not existing_event.event.internal_metadata.is_outlier():
  717. # ...then there's no need to persist it. We have it already.
  718. logger.info(
  719. "_process_pulled_event: Ignoring received event %s which we "
  720. "have already seen",
  721. event.event_id,
  722. )
  723. continue
  724. # While we have seen this event before, it was stored as an outlier.
  725. # We'll now persist it as a non-outlier.
  726. logger.info("De-outliering event %s", event_id)
  727. # Continue on with the events that are new to us.
  728. new_events.append(event)
  729. # We want to sort these by depth so we process them and
  730. # tell clients about them in order.
  731. sorted_events = sorted(new_events, key=lambda x: x.depth)
  732. for ev in sorted_events:
  733. with nested_logging_context(ev.event_id):
  734. await self._process_pulled_event(origin, ev, backfilled=backfilled)
  735. @trace
  736. @tag_args
  737. async def _process_pulled_event(
  738. self, origin: str, event: EventBase, backfilled: bool
  739. ) -> None:
  740. """Process a single event that we have pulled from a remote server
  741. Pulls in any events required to auth the event, persists the received event,
  742. and notifies clients, if appropriate.
  743. Assumes the event has already had its signatures and hashes checked.
  744. This is somewhat equivalent to on_receive_pdu, but applies somewhat different
  745. logic in the case that we are missing prev_events (in particular, it just
  746. requests the state at that point, rather than triggering a get_missing_events) -
  747. so is appropriate when we have pulled the event from a remote server, rather
  748. than having it pushed to us.
  749. Params:
  750. origin: The server we received this event from
  751. events: The received event
  752. backfilled: True if this is part of a historical batch of events (inhibits
  753. notification to clients, and validation of device keys.)
  754. """
  755. logger.info("Processing pulled event %s", event)
  756. # This function should not be used to persist outliers (use something
  757. # else) because this does a bunch of operations that aren't necessary
  758. # (extra work; in particular, it makes sure we have all the prev_events
  759. # and resolves the state across those prev events). If you happen to run
  760. # into a situation where the event you're trying to process/backfill is
  761. # marked as an `outlier`, then you should update that spot to return an
  762. # `EventBase` copy that doesn't have `outlier` flag set.
  763. #
  764. # `EventBase` is used to represent both an event we have not yet
  765. # persisted, and one that we have persisted and now keep in the cache.
  766. # In an ideal world this method would only be called with the first type
  767. # of event, but it turns out that's not actually the case and for
  768. # example, you could get an event from cache that is marked as an
  769. # `outlier` (fix up that spot though).
  770. assert not event.internal_metadata.is_outlier(), (
  771. "Outlier event passed to _process_pulled_event. "
  772. "To persist an event as a non-outlier, make sure to pass in a copy without `event.internal_metadata.outlier = true`."
  773. )
  774. event_id = event.event_id
  775. try:
  776. self._sanity_check_event(event)
  777. except SynapseError as err:
  778. logger.warning("Event %s failed sanity check: %s", event_id, err)
  779. await self._store.record_event_failed_pull_attempt(
  780. event.room_id, event_id, str(err)
  781. )
  782. return
  783. try:
  784. try:
  785. context = await self._compute_event_context_with_maybe_missing_prevs(
  786. origin, event
  787. )
  788. await self._process_received_pdu(
  789. origin,
  790. event,
  791. context,
  792. backfilled=backfilled,
  793. )
  794. except PartialStateConflictError:
  795. # The room was un-partial stated while we were processing the event.
  796. # Try once more, with full state this time.
  797. context = await self._compute_event_context_with_maybe_missing_prevs(
  798. origin, event
  799. )
  800. # We ought to have full state now, barring some unlikely race where we left and
  801. # rejoned the room in the background.
  802. if context.partial_state:
  803. raise AssertionError(
  804. f"Event {event.event_id} still has a partial resolved state "
  805. f"after room {event.room_id} was un-partial stated"
  806. )
  807. await self._process_received_pdu(
  808. origin,
  809. event,
  810. context,
  811. backfilled=backfilled,
  812. )
  813. except FederationPullAttemptBackoffError as exc:
  814. # Log a warning about why we failed to process the event (the error message
  815. # for `FederationPullAttemptBackoffError` is pretty good)
  816. logger.warning("_process_pulled_event: %s", exc)
  817. # We do not record a failed pull attempt when we backoff fetching a missing
  818. # `prev_event` because not being able to fetch the `prev_events` just means
  819. # we won't be able to de-outlier the pulled event. But we can still use an
  820. # `outlier` in the state/auth chain for another event. So we shouldn't stop
  821. # a downstream event from trying to pull it.
  822. #
  823. # This avoids a cascade of backoff for all events in the DAG downstream from
  824. # one event backoff upstream.
  825. except FederationError as e:
  826. await self._store.record_event_failed_pull_attempt(
  827. event.room_id, event_id, str(e)
  828. )
  829. if e.code == 403:
  830. logger.warning("Pulled event %s failed history check.", event_id)
  831. else:
  832. raise
  833. @trace
  834. async def _compute_event_context_with_maybe_missing_prevs(
  835. self, dest: str, event: EventBase
  836. ) -> EventContext:
  837. """Build an EventContext structure for a non-outlier event whose prev_events may
  838. be missing.
  839. This is used when we have pulled a batch of events from a remote server, and may
  840. not have all the prev_events.
  841. To build an EventContext, we need to calculate the state before the event. If we
  842. already have all the prev_events for `event`, we can simply use the state after
  843. the prev_events to calculate the state before `event`.
  844. Otherwise, the missing prevs become new backwards extremities, and we fall back
  845. to asking the remote server for the state after each missing `prev_event`,
  846. and resolving across them.
  847. That's ok provided we then resolve the state against other bits of the DAG
  848. before using it - in other words, that the received event `event` is not going
  849. to become the only forwards_extremity in the room (which will ensure that you
  850. can't just take over a room by sending an event, withholding its prev_events,
  851. and declaring yourself to be an admin in the subsequent state request).
  852. In other words: we should only call this method if `event` has been *pulled*
  853. as part of a batch of missing prev events, or similar.
  854. Params:
  855. dest: the remote server to ask for state at the missing prevs. Typically,
  856. this will be the server we got `event` from.
  857. event: an event to check for missing prevs.
  858. Returns:
  859. The event context.
  860. Raises:
  861. FederationPullAttemptBackoffError if we are are deliberately not attempting
  862. to pull the given event over federation because we've already done so
  863. recently and are backing off.
  864. FederationError if we fail to get the state from the remote server after any
  865. missing `prev_event`s.
  866. """
  867. room_id = event.room_id
  868. event_id = event.event_id
  869. prevs = set(event.prev_event_ids())
  870. seen = await self._store.have_events_in_timeline(prevs)
  871. missing_prevs = prevs - seen
  872. # If we've already recently attempted to pull this missing event, don't
  873. # try it again so soon. Since we have to fetch all of the prev_events, we can
  874. # bail early here if we find any to ignore.
  875. prevs_to_ignore = await self._store.get_event_ids_to_not_pull_from_backoff(
  876. room_id, missing_prevs
  877. )
  878. if len(prevs_to_ignore) > 0:
  879. raise FederationPullAttemptBackoffError(
  880. event_ids=prevs_to_ignore,
  881. message=f"While computing context for event={event_id}, not attempting to pull missing prev_event={prevs_to_ignore[0]} because we already tried to pull recently (backing off).",
  882. )
  883. if not missing_prevs:
  884. return await self._state_handler.compute_event_context(event)
  885. logger.info(
  886. "Event %s is missing prev_events %s: calculating state for a "
  887. "backwards extremity",
  888. event_id,
  889. shortstr(missing_prevs),
  890. )
  891. # Calculate the state after each of the previous events, and
  892. # resolve them to find the correct state at the current event.
  893. try:
  894. # Determine whether we may be about to retrieve partial state
  895. # Events may be un-partial stated right after we compute the partial state
  896. # flag, but that's okay, as long as the flag errs on the conservative side.
  897. partial_state_flags = await self._store.get_partial_state_events(seen)
  898. partial_state = any(partial_state_flags.values())
  899. # Get the state of the events we know about
  900. ours = await self._state_storage_controller.get_state_groups_ids(
  901. room_id, seen, await_full_state=False
  902. )
  903. # state_maps is a list of mappings from (type, state_key) to event_id
  904. state_maps: List[StateMap[str]] = list(ours.values())
  905. # we don't need this any more, let's delete it.
  906. del ours
  907. # Ask the remote server for the states we don't
  908. # know about
  909. for p in missing_prevs:
  910. logger.info("Requesting state after missing prev_event %s", p)
  911. with nested_logging_context(p):
  912. # note that if any of the missing prevs share missing state or
  913. # auth events, the requests to fetch those events are deduped
  914. # by the get_pdu_cache in federation_client.
  915. remote_state_map = (
  916. await self._get_state_ids_after_missing_prev_event(
  917. dest, room_id, p
  918. )
  919. )
  920. state_maps.append(remote_state_map)
  921. room_version = await self._store.get_room_version_id(room_id)
  922. state_map = await self._state_resolution_handler.resolve_events_with_store(
  923. room_id,
  924. room_version,
  925. state_maps,
  926. event_map={event_id: event},
  927. state_res_store=StateResolutionStore(self._store),
  928. )
  929. except Exception as e:
  930. logger.warning(
  931. "Error attempting to resolve state at missing prev_events: %s", e
  932. )
  933. raise FederationError(
  934. "ERROR",
  935. 403,
  936. "We can't get valid state history.",
  937. affected=event_id,
  938. )
  939. return await self._state_handler.compute_event_context(
  940. event, state_ids_before_event=state_map, partial_state=partial_state
  941. )
  942. @trace
  943. @tag_args
  944. async def _get_state_ids_after_missing_prev_event(
  945. self,
  946. destination: str,
  947. room_id: str,
  948. event_id: str,
  949. ) -> StateMap[str]:
  950. """Requests all of the room state at a given event from a remote homeserver.
  951. Args:
  952. destination: The remote homeserver to query for the state.
  953. room_id: The id of the room we're interested in.
  954. event_id: The id of the event we want the state at.
  955. Returns:
  956. The event ids of the state *after* the given event.
  957. Raises:
  958. InvalidResponseError: if the remote homeserver's response contains fields
  959. of the wrong type.
  960. """
  961. # It would be better if we could query the difference from our known
  962. # state to the given `event_id` so the sending server doesn't have to
  963. # send as much and we don't have to process as many events. For example
  964. # in a room like #matrix:matrix.org, we get 200k events (77k state_events, 122k
  965. # auth_events) from this call.
  966. #
  967. # Tracked by https://github.com/matrix-org/synapse/issues/13618
  968. (
  969. state_event_ids,
  970. auth_event_ids,
  971. ) = await self._federation_client.get_room_state_ids(
  972. destination, room_id, event_id=event_id
  973. )
  974. logger.debug(
  975. "state_ids returned %i state events, %i auth events",
  976. len(state_event_ids),
  977. len(auth_event_ids),
  978. )
  979. # Start by checking events we already have in the DB
  980. desired_events = set(state_event_ids)
  981. desired_events.add(event_id)
  982. logger.debug("Fetching %i events from cache/store", len(desired_events))
  983. have_events = await self._store.have_seen_events(room_id, desired_events)
  984. missing_desired_event_ids = desired_events - have_events
  985. logger.debug(
  986. "We are missing %i events (got %i)",
  987. len(missing_desired_event_ids),
  988. len(have_events),
  989. )
  990. # We probably won't need most of the auth events, so let's just check which
  991. # we have for now, rather than thrashing the event cache with them all
  992. # unnecessarily.
  993. # TODO: we probably won't actually need all of the auth events, since we
  994. # already have a bunch of the state events. It would be nice if the
  995. # federation api gave us a way of finding out which we actually need.
  996. missing_auth_event_ids = set(auth_event_ids) - have_events
  997. missing_auth_event_ids.difference_update(
  998. await self._store.have_seen_events(room_id, missing_auth_event_ids)
  999. )
  1000. logger.debug("We are also missing %i auth events", len(missing_auth_event_ids))
  1001. missing_event_ids = missing_desired_event_ids | missing_auth_event_ids
  1002. set_tag(
  1003. SynapseTags.RESULT_PREFIX + "missing_auth_event_ids",
  1004. str(missing_auth_event_ids),
  1005. )
  1006. set_tag(
  1007. SynapseTags.RESULT_PREFIX + "missing_auth_event_ids.length",
  1008. str(len(missing_auth_event_ids)),
  1009. )
  1010. set_tag(
  1011. SynapseTags.RESULT_PREFIX + "missing_desired_event_ids",
  1012. str(missing_desired_event_ids),
  1013. )
  1014. set_tag(
  1015. SynapseTags.RESULT_PREFIX + "missing_desired_event_ids.length",
  1016. str(len(missing_desired_event_ids)),
  1017. )
  1018. # Making an individual request for each of 1000s of events has a lot of
  1019. # overhead. On the other hand, we don't really want to fetch all of the events
  1020. # if we already have most of them.
  1021. #
  1022. # As an arbitrary heuristic, if we are missing more than 10% of the events, then
  1023. # we fetch the whole state.
  1024. #
  1025. # TODO: might it be better to have an API which lets us do an aggregate event
  1026. # request
  1027. if (len(missing_event_ids) * 10) >= len(auth_event_ids) + len(state_event_ids):
  1028. logger.debug("Requesting complete state from remote")
  1029. await self._get_state_and_persist(destination, room_id, event_id)
  1030. else:
  1031. logger.debug("Fetching %i events from remote", len(missing_event_ids))
  1032. await self._get_events_and_persist(
  1033. destination=destination, room_id=room_id, event_ids=missing_event_ids
  1034. )
  1035. # We now need to fill out the state map, which involves fetching the
  1036. # type and state key for each event ID in the state.
  1037. state_map = {}
  1038. event_metadata = await self._store.get_metadata_for_events(state_event_ids)
  1039. for state_event_id, metadata in event_metadata.items():
  1040. if metadata.room_id != room_id:
  1041. # This is a bogus situation, but since we may only discover it a long time
  1042. # after it happened, we try our best to carry on, by just omitting the
  1043. # bad events from the returned state set.
  1044. #
  1045. # This can happen if a remote server claims that the state or
  1046. # auth_events at an event in room A are actually events in room B
  1047. logger.warning(
  1048. "Remote server %s claims event %s in room %s is an auth/state "
  1049. "event in room %s",
  1050. destination,
  1051. state_event_id,
  1052. metadata.room_id,
  1053. room_id,
  1054. )
  1055. continue
  1056. if metadata.state_key is None:
  1057. logger.warning(
  1058. "Remote server gave us non-state event in state: %s", state_event_id
  1059. )
  1060. continue
  1061. state_map[(metadata.event_type, metadata.state_key)] = state_event_id
  1062. # if we couldn't get the prev event in question, that's a problem.
  1063. remote_event = await self._store.get_event(
  1064. event_id,
  1065. allow_none=True,
  1066. allow_rejected=True,
  1067. redact_behaviour=EventRedactBehaviour.as_is,
  1068. )
  1069. if not remote_event:
  1070. raise Exception("Unable to get missing prev_event %s" % (event_id,))
  1071. # missing state at that event is a warning, not a blocker
  1072. # XXX: this doesn't sound right? it means that we'll end up with incomplete
  1073. # state.
  1074. failed_to_fetch = desired_events - event_metadata.keys()
  1075. # `event_id` could be missing from `event_metadata` because it's not necessarily
  1076. # a state event. We've already checked that we've fetched it above.
  1077. failed_to_fetch.discard(event_id)
  1078. if failed_to_fetch:
  1079. logger.warning(
  1080. "Failed to fetch missing state events for %s %s",
  1081. event_id,
  1082. failed_to_fetch,
  1083. )
  1084. set_tag(
  1085. SynapseTags.RESULT_PREFIX + "failed_to_fetch",
  1086. str(failed_to_fetch),
  1087. )
  1088. set_tag(
  1089. SynapseTags.RESULT_PREFIX + "failed_to_fetch.length",
  1090. str(len(failed_to_fetch)),
  1091. )
  1092. if remote_event.is_state() and remote_event.rejected_reason is None:
  1093. state_map[
  1094. (remote_event.type, remote_event.state_key)
  1095. ] = remote_event.event_id
  1096. return state_map
  1097. @trace
  1098. @tag_args
  1099. async def _get_state_and_persist(
  1100. self, destination: str, room_id: str, event_id: str
  1101. ) -> None:
  1102. """Get the complete room state at a given event, and persist any new events
  1103. as outliers"""
  1104. room_version = await self._store.get_room_version(room_id)
  1105. auth_events, state_events = await self._federation_client.get_room_state(
  1106. destination, room_id, event_id=event_id, room_version=room_version
  1107. )
  1108. logger.info("/state returned %i events", len(auth_events) + len(state_events))
  1109. await self._auth_and_persist_outliers(
  1110. room_id, itertools.chain(auth_events, state_events)
  1111. )
  1112. # we also need the event itself.
  1113. if not await self._store.have_seen_event(room_id, event_id):
  1114. await self._get_events_and_persist(
  1115. destination=destination, room_id=room_id, event_ids=(event_id,)
  1116. )
  1117. @trace
  1118. async def _process_received_pdu(
  1119. self,
  1120. origin: str,
  1121. event: EventBase,
  1122. context: EventContext,
  1123. backfilled: bool = False,
  1124. ) -> None:
  1125. """Called when we have a new non-outlier event.
  1126. This is called when we have a new event to add to the room DAG. This can be
  1127. due to:
  1128. * events received directly via a /send request
  1129. * events retrieved via get_missing_events after a /send request
  1130. * events backfilled after a client request.
  1131. It's not currently used for events received from incoming send_{join,knock,leave}
  1132. requests (which go via on_send_membership_event), nor for joins created by a
  1133. remote join dance (which go via process_remote_join).
  1134. We need to do auth checks and put it through the StateHandler.
  1135. Args:
  1136. origin: server sending the event
  1137. event: event to be persisted
  1138. context: The `EventContext` to persist the event with.
  1139. backfilled: True if this is part of a historical batch of events (inhibits
  1140. notification to clients, and validation of device keys.)
  1141. PartialStateConflictError: if the room was un-partial stated in between
  1142. computing the state at the event and persisting it. The caller should
  1143. recompute `context` and retry exactly once when this happens.
  1144. """
  1145. logger.debug("Processing event: %s", event)
  1146. assert not event.internal_metadata.outlier
  1147. try:
  1148. await self._check_event_auth(origin, event, context)
  1149. except AuthError as e:
  1150. # This happens only if we couldn't find the auth events. We'll already have
  1151. # logged a warning, so now we just convert to a FederationError.
  1152. raise FederationError("ERROR", e.code, e.msg, affected=event.event_id)
  1153. if not backfilled and not context.rejected:
  1154. # For new (non-backfilled and non-outlier) events we check if the event
  1155. # passes auth based on the current state. If it doesn't then we
  1156. # "soft-fail" the event.
  1157. await self._check_for_soft_fail(event, context=context, origin=origin)
  1158. await self._run_push_actions_and_persist_event(event, context, backfilled)
  1159. await self._handle_marker_event(origin, event)
  1160. if backfilled or context.rejected:
  1161. return
  1162. await self._maybe_kick_guest_users(event)
  1163. # For encrypted messages we check that we know about the sending device,
  1164. # if we don't then we mark the device cache for that user as stale.
  1165. if event.type == EventTypes.Encrypted:
  1166. device_id = event.content.get("device_id")
  1167. sender_key = event.content.get("sender_key")
  1168. cached_devices = await self._store.get_cached_devices_for_user(event.sender)
  1169. resync = False # Whether we should resync device lists.
  1170. device = None
  1171. if device_id is not None:
  1172. device = cached_devices.get(device_id)
  1173. if device is None:
  1174. logger.info(
  1175. "Received event from remote device not in our cache: %s %s",
  1176. event.sender,
  1177. device_id,
  1178. )
  1179. resync = True
  1180. # We also check if the `sender_key` matches what we expect.
  1181. if sender_key is not None:
  1182. # Figure out what sender key we're expecting. If we know the
  1183. # device and recognize the algorithm then we can work out the
  1184. # exact key to expect. Otherwise check it matches any key we
  1185. # have for that device.
  1186. current_keys: Container[str] = []
  1187. if device:
  1188. keys = device.get("keys", {}).get("keys", {})
  1189. if (
  1190. event.content.get("algorithm")
  1191. == RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2
  1192. ):
  1193. # For this algorithm we expect a curve25519 key.
  1194. key_name = "curve25519:%s" % (device_id,)
  1195. current_keys = [keys.get(key_name)]
  1196. else:
  1197. # We don't know understand the algorithm, so we just
  1198. # check it matches a key for the device.
  1199. current_keys = keys.values()
  1200. elif device_id:
  1201. # We don't have any keys for the device ID.
  1202. pass
  1203. else:
  1204. # The event didn't include a device ID, so we just look for
  1205. # keys across all devices.
  1206. current_keys = [
  1207. key
  1208. for device in cached_devices.values()
  1209. for key in device.get("keys", {}).get("keys", {}).values()
  1210. ]
  1211. # We now check that the sender key matches (one of) the expected
  1212. # keys.
  1213. if sender_key not in current_keys:
  1214. logger.info(
  1215. "Received event from remote device with unexpected sender key: %s %s: %s",
  1216. event.sender,
  1217. device_id or "<no device_id>",
  1218. sender_key,
  1219. )
  1220. resync = True
  1221. if resync:
  1222. run_as_background_process(
  1223. "resync_device_due_to_pdu",
  1224. self._resync_device,
  1225. event.sender,
  1226. )
  1227. async def _resync_device(self, sender: str) -> None:
  1228. """We have detected that the device list for the given user may be out
  1229. of sync, so we try and resync them.
  1230. """
  1231. try:
  1232. await self._store.mark_remote_users_device_caches_as_stale((sender,))
  1233. # Immediately attempt a resync in the background
  1234. if self._config.worker.worker_app:
  1235. await self._user_device_resync(user_id=sender)
  1236. else:
  1237. await self._device_list_updater.user_device_resync(sender)
  1238. except Exception:
  1239. logger.exception("Failed to resync device for %s", sender)
  1240. @trace
  1241. async def _handle_marker_event(self, origin: str, marker_event: EventBase) -> None:
  1242. """Handles backfilling the insertion event when we receive a marker
  1243. event that points to one.
  1244. Args:
  1245. origin: Origin of the event. Will be called to get the insertion event
  1246. marker_event: The event to process
  1247. """
  1248. if marker_event.type != EventTypes.MSC2716_MARKER:
  1249. # Not a marker event
  1250. return
  1251. if marker_event.rejected_reason is not None:
  1252. # Rejected event
  1253. return
  1254. # Skip processing a marker event if the room version doesn't
  1255. # support it or the event is not from the room creator.
  1256. room_version = await self._store.get_room_version(marker_event.room_id)
  1257. create_event = await self._store.get_create_event_for_room(marker_event.room_id)
  1258. room_creator = create_event.content.get(EventContentFields.ROOM_CREATOR)
  1259. if not room_version.msc2716_historical and (
  1260. not self._config.experimental.msc2716_enabled
  1261. or marker_event.sender != room_creator
  1262. ):
  1263. return
  1264. logger.debug("_handle_marker_event: received %s", marker_event)
  1265. insertion_event_id = marker_event.content.get(
  1266. EventContentFields.MSC2716_INSERTION_EVENT_REFERENCE
  1267. )
  1268. if insertion_event_id is None:
  1269. # Nothing to retrieve then (invalid marker)
  1270. return
  1271. already_seen_insertion_event = await self._store.have_seen_event(
  1272. marker_event.room_id, insertion_event_id
  1273. )
  1274. if already_seen_insertion_event:
  1275. # No need to process a marker again if we have already seen the
  1276. # insertion event that it was pointing to
  1277. return
  1278. logger.debug(
  1279. "_handle_marker_event: backfilling insertion event %s", insertion_event_id
  1280. )
  1281. await self._get_events_and_persist(
  1282. origin,
  1283. marker_event.room_id,
  1284. [insertion_event_id],
  1285. )
  1286. insertion_event = await self._store.get_event(
  1287. insertion_event_id, allow_none=True
  1288. )
  1289. if insertion_event is None:
  1290. logger.warning(
  1291. "_handle_marker_event: server %s didn't return insertion event %s for marker %s",
  1292. origin,
  1293. insertion_event_id,
  1294. marker_event.event_id,
  1295. )
  1296. return
  1297. logger.debug(
  1298. "_handle_marker_event: succesfully backfilled insertion event %s from marker event %s",
  1299. insertion_event,
  1300. marker_event,
  1301. )
  1302. await self._store.insert_insertion_extremity(
  1303. insertion_event_id, marker_event.room_id
  1304. )
  1305. logger.debug(
  1306. "_handle_marker_event: insertion extremity added for %s from marker event %s",
  1307. insertion_event,
  1308. marker_event,
  1309. )
  1310. async def backfill_event_id(
  1311. self, destinations: List[str], room_id: str, event_id: str
  1312. ) -> PulledPduInfo:
  1313. """Backfill a single event and persist it as a non-outlier which means
  1314. we also pull in all of the state and auth events necessary for it.
  1315. Args:
  1316. destination: The homeserver to pull the given event_id from.
  1317. room_id: The room where the event is from.
  1318. event_id: The event ID to backfill.
  1319. Raises:
  1320. FederationError if we are unable to find the event from the destination
  1321. """
  1322. logger.info("backfill_event_id: event_id=%s", event_id)
  1323. room_version = await self._store.get_room_version(room_id)
  1324. pulled_pdu_info = await self._federation_client.get_pdu(
  1325. destinations,
  1326. event_id,
  1327. room_version,
  1328. )
  1329. if not pulled_pdu_info:
  1330. raise FederationError(
  1331. "ERROR",
  1332. 404,
  1333. f"Unable to find event_id={event_id} from remote servers to backfill.",
  1334. affected=event_id,
  1335. )
  1336. # Persist the event we just fetched, including pulling all of the state
  1337. # and auth events to de-outlier it. This also sets up the necessary
  1338. # `state_groups` for the event.
  1339. await self._process_pulled_events(
  1340. pulled_pdu_info.pull_origin,
  1341. [pulled_pdu_info.pdu],
  1342. # Prevent notifications going to clients
  1343. backfilled=True,
  1344. )
  1345. return pulled_pdu_info
  1346. @trace
  1347. @tag_args
  1348. async def _get_events_and_persist(
  1349. self, destination: str, room_id: str, event_ids: Collection[str]
  1350. ) -> None:
  1351. """Fetch the given events from a server, and persist them as outliers.
  1352. This function *does not* recursively get missing auth events of the
  1353. newly fetched events. Callers must include in the `event_ids` argument
  1354. any missing events from the auth chain.
  1355. Logs a warning if we can't find the given event.
  1356. """
  1357. room_version = await self._store.get_room_version(room_id)
  1358. events: List[EventBase] = []
  1359. async def get_event(event_id: str) -> None:
  1360. with nested_logging_context(event_id):
  1361. try:
  1362. pulled_pdu_info = await self._federation_client.get_pdu(
  1363. [destination],
  1364. event_id,
  1365. room_version,
  1366. )
  1367. if pulled_pdu_info is None:
  1368. logger.warning(
  1369. "Server %s didn't return event %s",
  1370. destination,
  1371. event_id,
  1372. )
  1373. return
  1374. events.append(pulled_pdu_info.pdu)
  1375. except Exception as e:
  1376. logger.warning(
  1377. "Error fetching missing state/auth event %s: %s %s",
  1378. event_id,
  1379. type(e),
  1380. e,
  1381. )
  1382. await concurrently_execute(get_event, event_ids, 5)
  1383. logger.info("Fetched %i events of %i requested", len(events), len(event_ids))
  1384. await self._auth_and_persist_outliers(room_id, events)
  1385. @trace
  1386. async def _auth_and_persist_outliers(
  1387. self, room_id: str, events: Iterable[EventBase]
  1388. ) -> None:
  1389. """Persist a batch of outlier events fetched from remote servers.
  1390. We first sort the events to make sure that we process each event's auth_events
  1391. before the event itself.
  1392. We then mark the events as outliers, persist them to the database, and, where
  1393. appropriate (eg, an invite), awake the notifier.
  1394. Params:
  1395. room_id: the room that the events are meant to be in (though this has
  1396. not yet been checked)
  1397. events: the events that have been fetched
  1398. """
  1399. event_map = {event.event_id: event for event in events}
  1400. event_ids = event_map.keys()
  1401. set_tag(
  1402. SynapseTags.FUNC_ARG_PREFIX + "event_ids",
  1403. str(event_ids),
  1404. )
  1405. set_tag(
  1406. SynapseTags.FUNC_ARG_PREFIX + "event_ids.length",
  1407. str(len(event_ids)),
  1408. )
  1409. # filter out any events we have already seen. This might happen because
  1410. # the events were eagerly pushed to us (eg, during a room join), or because
  1411. # another thread has raced against us since we decided to request the event.
  1412. #
  1413. # This is just an optimisation, so it doesn't need to be watertight - the event
  1414. # persister does another round of deduplication.
  1415. seen_remotes = await self._store.have_seen_events(room_id, event_map.keys())
  1416. for s in seen_remotes:
  1417. event_map.pop(s, None)
  1418. # XXX: it might be possible to kick this process off in parallel with fetching
  1419. # the events.
  1420. while event_map:
  1421. # build a list of events whose auth events are not in the queue.
  1422. roots = tuple(
  1423. ev
  1424. for ev in event_map.values()
  1425. if not any(aid in event_map for aid in ev.auth_event_ids())
  1426. )
  1427. if not roots:
  1428. # if *none* of the remaining events are ready, that means
  1429. # we have a loop. This either means a bug in our logic, or that
  1430. # somebody has managed to create a loop (which requires finding a
  1431. # hash collision in room v2 and later).
  1432. logger.warning(
  1433. "Loop found in auth events while fetching missing state/auth "
  1434. "events: %s",
  1435. shortstr(event_map.keys()),
  1436. )
  1437. return
  1438. logger.info(
  1439. "Persisting %i of %i remaining outliers: %s",
  1440. len(roots),
  1441. len(event_map),
  1442. shortstr(e.event_id for e in roots),
  1443. )
  1444. await self._auth_and_persist_outliers_inner(room_id, roots)
  1445. for ev in roots:
  1446. del event_map[ev.event_id]
  1447. async def _auth_and_persist_outliers_inner(
  1448. self, room_id: str, fetched_events: Collection[EventBase]
  1449. ) -> None:
  1450. """Helper for _auth_and_persist_outliers
  1451. Persists a batch of events where we have (theoretically) already persisted all
  1452. of their auth events.
  1453. Marks the events as outliers, auths them, persists them to the database, and,
  1454. where appropriate (eg, an invite), awakes the notifier.
  1455. Params:
  1456. origin: where the events came from
  1457. room_id: the room that the events are meant to be in (though this has
  1458. not yet been checked)
  1459. fetched_events: the events to persist
  1460. """
  1461. # get all the auth events for all the events in this batch. By now, they should
  1462. # have been persisted.
  1463. auth_events = {
  1464. aid for event in fetched_events for aid in event.auth_event_ids()
  1465. }
  1466. persisted_events = await self._store.get_events(
  1467. auth_events,
  1468. allow_rejected=True,
  1469. )
  1470. events_and_contexts_to_persist: List[Tuple[EventBase, EventContext]] = []
  1471. async def prep(event: EventBase) -> None:
  1472. with nested_logging_context(suffix=event.event_id):
  1473. auth = []
  1474. for auth_event_id in event.auth_event_ids():
  1475. ae = persisted_events.get(auth_event_id)
  1476. if not ae:
  1477. # the fact we can't find the auth event doesn't mean it doesn't
  1478. # exist, which means it is premature to reject `event`. Instead we
  1479. # just ignore it for now.
  1480. logger.warning(
  1481. "Dropping event %s, which relies on auth_event %s, which could not be found",
  1482. event,
  1483. auth_event_id,
  1484. )
  1485. return
  1486. auth.append(ae)
  1487. # we're not bothering about room state, so flag the event as an outlier.
  1488. event.internal_metadata.outlier = True
  1489. context = EventContext.for_outlier(self._storage_controllers)
  1490. try:
  1491. validate_event_for_room_version(event)
  1492. await check_state_independent_auth_rules(self._store, event)
  1493. check_state_dependent_auth_rules(event, auth)
  1494. except AuthError as e:
  1495. logger.warning("Rejecting %r because %s", event, e)
  1496. context.rejected = RejectedReason.AUTH_ERROR
  1497. except EventSizeError as e:
  1498. if e.unpersistable:
  1499. # This event is completely unpersistable.
  1500. raise e
  1501. # Otherwise, we are somewhat lenient and just persist the event
  1502. # as rejected, for moderate compatibility with older Synapse
  1503. # versions.
  1504. logger.warning("While validating received event %r: %s", event, e)
  1505. context.rejected = RejectedReason.OVERSIZED_EVENT
  1506. events_and_contexts_to_persist.append((event, context))
  1507. for event in fetched_events:
  1508. await prep(event)
  1509. await self.persist_events_and_notify(
  1510. room_id,
  1511. events_and_contexts_to_persist,
  1512. # Mark these events backfilled as they're historic events that will
  1513. # eventually be backfilled. For example, missing events we fetch
  1514. # during backfill should be marked as backfilled as well.
  1515. backfilled=True,
  1516. )
  1517. @trace
  1518. async def _check_event_auth(
  1519. self, origin: Optional[str], event: EventBase, context: EventContext
  1520. ) -> None:
  1521. """
  1522. Checks whether an event should be rejected (for failing auth checks).
  1523. Args:
  1524. origin: The host the event originates from. This is used to fetch
  1525. any missing auth events. It can be set to None, but only if we are
  1526. sure that we already have all the auth events.
  1527. event: The event itself.
  1528. context:
  1529. The event context.
  1530. Raises:
  1531. AuthError if we were unable to find copies of the event's auth events.
  1532. (Most other failures just cause us to set `context.rejected`.)
  1533. """
  1534. # This method should only be used for non-outliers
  1535. assert not event.internal_metadata.outlier
  1536. # first of all, check that the event itself is valid.
  1537. try:
  1538. validate_event_for_room_version(event)
  1539. except AuthError as e:
  1540. logger.warning("While validating received event %r: %s", event, e)
  1541. # TODO: use a different rejected reason here?
  1542. context.rejected = RejectedReason.AUTH_ERROR
  1543. return
  1544. except EventSizeError as e:
  1545. if e.unpersistable:
  1546. # This event is completely unpersistable.
  1547. raise e
  1548. # Otherwise, we are somewhat lenient and just persist the event
  1549. # as rejected, for moderate compatibility with older Synapse
  1550. # versions.
  1551. logger.warning("While validating received event %r: %s", event, e)
  1552. context.rejected = RejectedReason.OVERSIZED_EVENT
  1553. return
  1554. # next, check that we have all of the event's auth events.
  1555. #
  1556. # Note that this can raise AuthError, which we want to propagate to the
  1557. # caller rather than swallow with `context.rejected` (since we cannot be
  1558. # certain that there is a permanent problem with the event).
  1559. claimed_auth_events = await self._load_or_fetch_auth_events_for_event(
  1560. origin, event
  1561. )
  1562. set_tag(
  1563. SynapseTags.RESULT_PREFIX + "claimed_auth_events",
  1564. str([ev.event_id for ev in claimed_auth_events]),
  1565. )
  1566. set_tag(
  1567. SynapseTags.RESULT_PREFIX + "claimed_auth_events.length",
  1568. str(len(claimed_auth_events)),
  1569. )
  1570. # ... and check that the event passes auth at those auth events.
  1571. # https://spec.matrix.org/v1.3/server-server-api/#checks-performed-on-receipt-of-a-pdu:
  1572. # 4. Passes authorization rules based on the event’s auth events,
  1573. # otherwise it is rejected.
  1574. try:
  1575. await check_state_independent_auth_rules(self._store, event)
  1576. check_state_dependent_auth_rules(event, claimed_auth_events)
  1577. except AuthError as e:
  1578. logger.warning(
  1579. "While checking auth of %r against auth_events: %s", event, e
  1580. )
  1581. context.rejected = RejectedReason.AUTH_ERROR
  1582. return
  1583. # now check the auth rules pass against the room state before the event
  1584. # https://spec.matrix.org/v1.3/server-server-api/#checks-performed-on-receipt-of-a-pdu:
  1585. # 5. Passes authorization rules based on the state before the event,
  1586. # otherwise it is rejected.
  1587. #
  1588. # ... however, if we only have partial state for the room, then there is a good
  1589. # chance that we'll be missing some of the state needed to auth the new event.
  1590. # So, we state-resolve the auth events that we are given against the state that
  1591. # we know about, which ensures things like bans are applied. (Note that we'll
  1592. # already have checked we have all the auth events, in
  1593. # _load_or_fetch_auth_events_for_event above)
  1594. if context.partial_state:
  1595. room_version = await self._store.get_room_version_id(event.room_id)
  1596. local_state_id_map = await context.get_prev_state_ids()
  1597. claimed_auth_events_id_map = {
  1598. (ev.type, ev.state_key): ev.event_id for ev in claimed_auth_events
  1599. }
  1600. state_for_auth_id_map = (
  1601. await self._state_resolution_handler.resolve_events_with_store(
  1602. event.room_id,
  1603. room_version,
  1604. [local_state_id_map, claimed_auth_events_id_map],
  1605. event_map=None,
  1606. state_res_store=StateResolutionStore(self._store),
  1607. )
  1608. )
  1609. else:
  1610. event_types = event_auth.auth_types_for_event(event.room_version, event)
  1611. state_for_auth_id_map = await context.get_prev_state_ids(
  1612. StateFilter.from_types(event_types)
  1613. )
  1614. calculated_auth_event_ids = self._event_auth_handler.compute_auth_events(
  1615. event, state_for_auth_id_map, for_verification=True
  1616. )
  1617. # if those are the same, we're done here.
  1618. if collections.Counter(event.auth_event_ids()) == collections.Counter(
  1619. calculated_auth_event_ids
  1620. ):
  1621. return
  1622. # otherwise, re-run the auth checks based on what we calculated.
  1623. calculated_auth_events = await self._store.get_events_as_list(
  1624. calculated_auth_event_ids
  1625. )
  1626. # log the differences
  1627. claimed_auth_event_map = {(e.type, e.state_key): e for e in claimed_auth_events}
  1628. calculated_auth_event_map = {
  1629. (e.type, e.state_key): e for e in calculated_auth_events
  1630. }
  1631. logger.info(
  1632. "event's auth_events are different to our calculated auth_events. "
  1633. "Claimed but not calculated: %s. Calculated but not claimed: %s",
  1634. [
  1635. ev
  1636. for k, ev in claimed_auth_event_map.items()
  1637. if k not in calculated_auth_event_map
  1638. or calculated_auth_event_map[k].event_id != ev.event_id
  1639. ],
  1640. [
  1641. ev
  1642. for k, ev in calculated_auth_event_map.items()
  1643. if k not in claimed_auth_event_map
  1644. or claimed_auth_event_map[k].event_id != ev.event_id
  1645. ],
  1646. )
  1647. try:
  1648. check_state_dependent_auth_rules(event, calculated_auth_events)
  1649. except AuthError as e:
  1650. logger.warning(
  1651. "While checking auth of %r against room state before the event: %s",
  1652. event,
  1653. e,
  1654. )
  1655. context.rejected = RejectedReason.AUTH_ERROR
  1656. @trace
  1657. async def _maybe_kick_guest_users(self, event: EventBase) -> None:
  1658. if event.type != EventTypes.GuestAccess:
  1659. return
  1660. guest_access = event.content.get(EventContentFields.GUEST_ACCESS)
  1661. if guest_access == GuestAccess.CAN_JOIN:
  1662. return
  1663. current_state = await self._storage_controllers.state.get_current_state(
  1664. event.room_id
  1665. )
  1666. current_state_list = list(current_state.values())
  1667. await self._get_room_member_handler().kick_guest_users(current_state_list)
  1668. async def _check_for_soft_fail(
  1669. self,
  1670. event: EventBase,
  1671. context: EventContext,
  1672. origin: str,
  1673. ) -> None:
  1674. """Checks if we should soft fail the event; if so, marks the event as
  1675. such.
  1676. Does nothing for events in rooms with partial state, since we may not have an
  1677. accurate membership event for the sender in the current state.
  1678. Args:
  1679. event
  1680. context: The `EventContext` which we are about to persist the event with.
  1681. origin: The host the event originates from.
  1682. """
  1683. if await self._store.is_partial_state_room(event.room_id):
  1684. # We might not know the sender's membership in the current state, so don't
  1685. # soft fail anything. Even if we do have a membership for the sender in the
  1686. # current state, it may have been derived from state resolution between
  1687. # partial and full state and may not be accurate.
  1688. return
  1689. extrem_ids_list = await self._store.get_latest_event_ids_in_room(event.room_id)
  1690. extrem_ids = set(extrem_ids_list)
  1691. prev_event_ids = set(event.prev_event_ids())
  1692. if extrem_ids == prev_event_ids:
  1693. # If they're the same then the current state is the same as the
  1694. # state at the event, so no point rechecking auth for soft fail.
  1695. return
  1696. room_version = await self._store.get_room_version_id(event.room_id)
  1697. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  1698. # The event types we want to pull from the "current" state.
  1699. auth_types = auth_types_for_event(room_version_obj, event)
  1700. # Calculate the "current state".
  1701. seen_event_ids = await self._store.have_events_in_timeline(prev_event_ids)
  1702. has_missing_prevs = bool(prev_event_ids - seen_event_ids)
  1703. if has_missing_prevs:
  1704. # We don't have all the prev_events of this event, which means we have a
  1705. # gap in the graph, and the new event is going to become a new backwards
  1706. # extremity.
  1707. #
  1708. # In this case we want to be a little careful as we might have been
  1709. # down for a while and have an incorrect view of the current state,
  1710. # however we still want to do checks as gaps are easy to
  1711. # maliciously manufacture.
  1712. #
  1713. # So we use a "current state" that is actually a state
  1714. # resolution across the current forward extremities and the
  1715. # given state at the event. This should correctly handle cases
  1716. # like bans, especially with state res v2.
  1717. state_sets_d = await self._state_storage_controller.get_state_groups_ids(
  1718. event.room_id, extrem_ids
  1719. )
  1720. state_sets: List[StateMap[str]] = list(state_sets_d.values())
  1721. state_ids = await context.get_prev_state_ids()
  1722. state_sets.append(state_ids)
  1723. current_state_ids = (
  1724. await self._state_resolution_handler.resolve_events_with_store(
  1725. event.room_id,
  1726. room_version,
  1727. state_sets,
  1728. event_map=None,
  1729. state_res_store=StateResolutionStore(self._store),
  1730. )
  1731. )
  1732. else:
  1733. current_state_ids = (
  1734. await self._state_storage_controller.get_current_state_ids(
  1735. event.room_id, StateFilter.from_types(auth_types)
  1736. )
  1737. )
  1738. logger.debug(
  1739. "Doing soft-fail check for %s: state %s",
  1740. event.event_id,
  1741. current_state_ids,
  1742. )
  1743. # Now check if event pass auth against said current state
  1744. current_state_ids_list = [
  1745. e for k, e in current_state_ids.items() if k in auth_types
  1746. ]
  1747. current_auth_events = await self._store.get_events_as_list(
  1748. current_state_ids_list
  1749. )
  1750. try:
  1751. check_state_dependent_auth_rules(event, current_auth_events)
  1752. except AuthError as e:
  1753. logger.warning(
  1754. "Soft-failing %r (from %s) because %s",
  1755. event,
  1756. e,
  1757. origin,
  1758. extra={
  1759. "room_id": event.room_id,
  1760. "mxid": event.sender,
  1761. "hs": origin,
  1762. },
  1763. )
  1764. soft_failed_event_counter.inc()
  1765. event.internal_metadata.soft_failed = True
  1766. async def _load_or_fetch_auth_events_for_event(
  1767. self, destination: Optional[str], event: EventBase
  1768. ) -> Collection[EventBase]:
  1769. """Fetch this event's auth_events, from database or remote
  1770. Loads any of the auth_events that we already have from the database/cache. If
  1771. there are any that are missing, calls /event_auth to get the complete auth
  1772. chain for the event (and then attempts to load the auth_events again).
  1773. If any of the auth_events cannot be found, raises an AuthError. This can happen
  1774. for a number of reasons; eg: the events don't exist, or we were unable to talk
  1775. to `destination`, or we couldn't validate the signature on the event (which
  1776. in turn has multiple potential causes).
  1777. Args:
  1778. destination: where to send the /event_auth request. Typically the server
  1779. that sent us `event` in the first place.
  1780. If this is None, no attempt is made to load any missing auth events:
  1781. rather, an AssertionError is raised if there are any missing events.
  1782. event: the event whose auth_events we want
  1783. Returns:
  1784. all of the events listed in `event.auth_events_ids`, after deduplication
  1785. Raises:
  1786. AssertionError if some auth events were missing and no `destination` was
  1787. supplied.
  1788. AuthError if we were unable to fetch the auth_events for any reason.
  1789. """
  1790. event_auth_event_ids = set(event.auth_event_ids())
  1791. event_auth_events = await self._store.get_events(
  1792. event_auth_event_ids, allow_rejected=True
  1793. )
  1794. missing_auth_event_ids = event_auth_event_ids.difference(
  1795. event_auth_events.keys()
  1796. )
  1797. if not missing_auth_event_ids:
  1798. return event_auth_events.values()
  1799. if destination is None:
  1800. # this shouldn't happen: destination must be set unless we know we have already
  1801. # persisted the auth events.
  1802. raise AssertionError(
  1803. "_load_or_fetch_auth_events_for_event() called with no destination for "
  1804. "an event with missing auth_events"
  1805. )
  1806. logger.info(
  1807. "Event %s refers to unknown auth events %s: fetching auth chain",
  1808. event,
  1809. missing_auth_event_ids,
  1810. )
  1811. try:
  1812. await self._get_remote_auth_chain_for_event(
  1813. destination, event.room_id, event.event_id
  1814. )
  1815. except Exception as e:
  1816. logger.warning("Failed to get auth chain for %s: %s", event, e)
  1817. # in this case, it's very likely we still won't have all the auth
  1818. # events - but we pick that up below.
  1819. # try to fetch the auth events we missed list time.
  1820. extra_auth_events = await self._store.get_events(
  1821. missing_auth_event_ids, allow_rejected=True
  1822. )
  1823. missing_auth_event_ids.difference_update(extra_auth_events.keys())
  1824. event_auth_events.update(extra_auth_events)
  1825. if not missing_auth_event_ids:
  1826. return event_auth_events.values()
  1827. # we still don't have all the auth events.
  1828. logger.warning(
  1829. "Missing auth events for %s: %s",
  1830. event,
  1831. shortstr(missing_auth_event_ids),
  1832. )
  1833. # the fact we can't find the auth event doesn't mean it doesn't
  1834. # exist, which means it is premature to store `event` as rejected.
  1835. # instead we raise an AuthError, which will make the caller ignore it.
  1836. raise AuthError(code=HTTPStatus.FORBIDDEN, msg="Auth events could not be found")
  1837. @trace
  1838. @tag_args
  1839. async def _get_remote_auth_chain_for_event(
  1840. self, destination: str, room_id: str, event_id: str
  1841. ) -> None:
  1842. """If we are missing some of an event's auth events, attempt to request them
  1843. Args:
  1844. destination: where to fetch the auth tree from
  1845. room_id: the room in which we are lacking auth events
  1846. event_id: the event for which we are lacking auth events
  1847. """
  1848. try:
  1849. remote_events = await self._federation_client.get_event_auth(
  1850. destination, room_id, event_id
  1851. )
  1852. except RequestSendFailed as e1:
  1853. # The other side isn't around or doesn't implement the
  1854. # endpoint, so lets just bail out.
  1855. logger.info("Failed to get event auth from remote: %s", e1)
  1856. return
  1857. logger.info("/event_auth returned %i events", len(remote_events))
  1858. # `event` may be returned, but we should not yet process it.
  1859. remote_auth_events = (e for e in remote_events if e.event_id != event_id)
  1860. await self._auth_and_persist_outliers(room_id, remote_auth_events)
  1861. @trace
  1862. async def _run_push_actions_and_persist_event(
  1863. self, event: EventBase, context: EventContext, backfilled: bool = False
  1864. ) -> None:
  1865. """Run the push actions for a received event, and persist it.
  1866. Args:
  1867. event: The event itself.
  1868. context: The event context.
  1869. backfilled: True if the event was backfilled.
  1870. PartialStateConflictError: if attempting to persist a partial state event in
  1871. a room that has been un-partial stated.
  1872. """
  1873. # this method should not be called on outliers (those code paths call
  1874. # persist_events_and_notify directly.)
  1875. assert not event.internal_metadata.outlier
  1876. if not backfilled and not context.rejected:
  1877. min_depth = await self._store.get_min_depth(event.room_id)
  1878. if min_depth is None or min_depth > event.depth:
  1879. # XXX richvdh 2021/10/07: I don't really understand what this
  1880. # condition is doing. I think it's trying not to send pushes
  1881. # for events that predate our join - but that's not really what
  1882. # min_depth means, and anyway ancient events are a more general
  1883. # problem.
  1884. #
  1885. # for now I'm just going to log about it.
  1886. logger.info(
  1887. "Skipping push actions for old event with depth %s < %s",
  1888. event.depth,
  1889. min_depth,
  1890. )
  1891. else:
  1892. await self._bulk_push_rule_evaluator.action_for_events_by_user(
  1893. [(event, context)]
  1894. )
  1895. try:
  1896. await self.persist_events_and_notify(
  1897. event.room_id, [(event, context)], backfilled=backfilled
  1898. )
  1899. except Exception:
  1900. await self._store.remove_push_actions_from_staging(event.event_id)
  1901. raise
  1902. async def persist_events_and_notify(
  1903. self,
  1904. room_id: str,
  1905. event_and_contexts: Sequence[Tuple[EventBase, EventContext]],
  1906. backfilled: bool = False,
  1907. ) -> int:
  1908. """Persists events and tells the notifier/pushers about them, if
  1909. necessary.
  1910. Args:
  1911. room_id: The room ID of events being persisted.
  1912. event_and_contexts: Sequence of events with their associated
  1913. context that should be persisted. All events must belong to
  1914. the same room.
  1915. backfilled: Whether these events are a result of
  1916. backfilling or not
  1917. Returns:
  1918. The stream ID after which all events have been persisted.
  1919. Raises:
  1920. PartialStateConflictError: if attempting to persist a partial state event in
  1921. a room that has been un-partial stated.
  1922. """
  1923. if not event_and_contexts:
  1924. return self._store.get_room_max_stream_ordering()
  1925. instance = self._config.worker.events_shard_config.get_instance(room_id)
  1926. if instance != self._instance_name:
  1927. # Limit the number of events sent over replication. We choose 200
  1928. # here as that is what we default to in `max_request_body_size(..)`
  1929. result = {}
  1930. try:
  1931. for batch in batch_iter(event_and_contexts, 200):
  1932. result = await self._send_events(
  1933. instance_name=instance,
  1934. store=self._store,
  1935. room_id=room_id,
  1936. event_and_contexts=batch,
  1937. backfilled=backfilled,
  1938. )
  1939. except SynapseError as e:
  1940. if e.code == HTTPStatus.CONFLICT:
  1941. raise PartialStateConflictError()
  1942. raise
  1943. return result["max_stream_id"]
  1944. else:
  1945. assert self._storage_controllers.persistence
  1946. # Note that this returns the events that were persisted, which may not be
  1947. # the same as were passed in if some were deduplicated due to transaction IDs.
  1948. (
  1949. events,
  1950. max_stream_token,
  1951. ) = await self._storage_controllers.persistence.persist_events(
  1952. event_and_contexts, backfilled=backfilled
  1953. )
  1954. # After persistence we always need to notify replication there may
  1955. # be new data.
  1956. self._notifier.notify_replication()
  1957. if self._ephemeral_messages_enabled:
  1958. for event in events:
  1959. # If there's an expiry timestamp on the event, schedule its expiry.
  1960. self._message_handler.maybe_schedule_expiry(event)
  1961. if not backfilled: # Never notify for backfilled events
  1962. with start_active_span("notify_persisted_events"):
  1963. set_tag(
  1964. SynapseTags.RESULT_PREFIX + "event_ids",
  1965. str([ev.event_id for ev in events]),
  1966. )
  1967. set_tag(
  1968. SynapseTags.RESULT_PREFIX + "event_ids.length",
  1969. str(len(events)),
  1970. )
  1971. for event in events:
  1972. await self._notify_persisted_event(event, max_stream_token)
  1973. return max_stream_token.stream
  1974. async def _notify_persisted_event(
  1975. self, event: EventBase, max_stream_token: RoomStreamToken
  1976. ) -> None:
  1977. """Checks to see if notifier/pushers should be notified about the
  1978. event or not.
  1979. Args:
  1980. event:
  1981. max_stream_token: The max_stream_id returned by persist_events
  1982. """
  1983. extra_users = []
  1984. if event.type == EventTypes.Member:
  1985. target_user_id = event.state_key
  1986. # We notify for memberships if its an invite for one of our
  1987. # users
  1988. if event.internal_metadata.is_outlier():
  1989. if event.membership != Membership.INVITE:
  1990. if not self._is_mine_id(target_user_id):
  1991. return
  1992. target_user = UserID.from_string(target_user_id)
  1993. extra_users.append(target_user)
  1994. elif event.internal_metadata.is_outlier():
  1995. return
  1996. # the event has been persisted so it should have a stream ordering.
  1997. assert event.internal_metadata.stream_ordering
  1998. event_pos = PersistedEventPosition(
  1999. self._instance_name, event.internal_metadata.stream_ordering
  2000. )
  2001. await self._notifier.on_new_room_events(
  2002. [(event, event_pos)], max_stream_token, extra_users=extra_users
  2003. )
  2004. if event.type == EventTypes.Member and event.membership == Membership.JOIN:
  2005. # TODO retrieve the previous state, and exclude join -> join transitions
  2006. self._notifier.notify_user_joined_room(event.event_id, event.room_id)
  2007. def _sanity_check_event(self, ev: EventBase) -> None:
  2008. """
  2009. Do some early sanity checks of a received event
  2010. In particular, checks it doesn't have an excessive number of
  2011. prev_events or auth_events, which could cause a huge state resolution
  2012. or cascade of event fetches.
  2013. Args:
  2014. ev: event to be checked
  2015. Raises:
  2016. SynapseError if the event does not pass muster
  2017. """
  2018. if len(ev.prev_event_ids()) > 20:
  2019. logger.warning(
  2020. "Rejecting event %s which has %i prev_events",
  2021. ev.event_id,
  2022. len(ev.prev_event_ids()),
  2023. )
  2024. raise SynapseError(HTTPStatus.BAD_REQUEST, "Too many prev_events")
  2025. if len(ev.auth_event_ids()) > 10:
  2026. logger.warning(
  2027. "Rejecting event %s which has %i auth_events",
  2028. ev.event_id,
  2029. len(ev.auth_event_ids()),
  2030. )
  2031. raise SynapseError(HTTPStatus.BAD_REQUEST, "Too many auth_events")