visibility.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. # Copyright 2014 - 2016 OpenMarket Ltd
  2. # Copyright (C) The Matrix.org Foundation C.I.C. 2022
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from enum import Enum, auto
  17. from typing import (
  18. Collection,
  19. Dict,
  20. FrozenSet,
  21. List,
  22. Mapping,
  23. Optional,
  24. Sequence,
  25. Set,
  26. Tuple,
  27. )
  28. import attr
  29. from typing_extensions import Final
  30. from synapse.api.constants import EventTypes, HistoryVisibility, Membership
  31. from synapse.events import EventBase
  32. from synapse.events.snapshot import EventContext
  33. from synapse.events.utils import prune_event
  34. from synapse.logging.opentracing import trace
  35. from synapse.storage.controllers import StorageControllers
  36. from synapse.storage.databases.main import DataStore
  37. from synapse.types import RetentionPolicy, StateMap, get_domain_from_id
  38. from synapse.types.state import StateFilter
  39. from synapse.util import Clock
  40. logger = logging.getLogger(__name__)
  41. filtered_event_logger = logging.getLogger("synapse.visibility.filtered_event_debug")
  42. VISIBILITY_PRIORITY = (
  43. HistoryVisibility.WORLD_READABLE,
  44. HistoryVisibility.SHARED,
  45. HistoryVisibility.INVITED,
  46. HistoryVisibility.JOINED,
  47. )
  48. MEMBERSHIP_PRIORITY = (
  49. Membership.JOIN,
  50. Membership.INVITE,
  51. Membership.KNOCK,
  52. Membership.LEAVE,
  53. Membership.BAN,
  54. )
  55. _HISTORY_VIS_KEY: Final[Tuple[str, str]] = (EventTypes.RoomHistoryVisibility, "")
  56. @trace
  57. async def filter_events_for_client(
  58. storage: StorageControllers,
  59. user_id: str,
  60. events: List[EventBase],
  61. is_peeking: bool = False,
  62. always_include_ids: FrozenSet[str] = frozenset(),
  63. filter_send_to_client: bool = True,
  64. ) -> List[EventBase]:
  65. """
  66. Check which events a user is allowed to see. If the user can see the event but its
  67. sender asked for their data to be erased, prune the content of the event.
  68. Args:
  69. storage
  70. user_id: user id to be checked
  71. events: sequence of events to be checked
  72. is_peeking: should be True if:
  73. * the user is not currently a member of the room, and:
  74. * the user has not been a member of the room since the given
  75. events
  76. always_include_ids: set of event ids to specifically include, if present
  77. in events (unless sender is ignored)
  78. filter_send_to_client: Whether we're checking an event that's going to be
  79. sent to a client. This might not always be the case since this function can
  80. also be called to check whether a user can see the state at a given point.
  81. Returns:
  82. The filtered events.
  83. """
  84. # Filter out events that have been soft failed so that we don't relay them
  85. # to clients.
  86. events_before_filtering = events
  87. events = [e for e in events if not e.internal_metadata.is_soft_failed()]
  88. if len(events_before_filtering) != len(events):
  89. if filtered_event_logger.isEnabledFor(logging.DEBUG):
  90. filtered_event_logger.debug(
  91. "filter_events_for_client: Filtered out soft-failed events: Before=%s, After=%s",
  92. [event.event_id for event in events_before_filtering],
  93. [event.event_id for event in events],
  94. )
  95. types = (_HISTORY_VIS_KEY, (EventTypes.Member, user_id))
  96. # we exclude outliers at this point, and then handle them separately later
  97. event_id_to_state = await storage.state.get_state_for_events(
  98. frozenset(e.event_id for e in events if not e.internal_metadata.outlier),
  99. state_filter=StateFilter.from_types(types),
  100. )
  101. # Get the users who are ignored by the requesting user.
  102. ignore_list = await storage.main.ignored_users(user_id)
  103. erased_senders = await storage.main.are_users_erased(e.sender for e in events)
  104. if filter_send_to_client:
  105. room_ids = {e.room_id for e in events}
  106. retention_policies: Dict[str, RetentionPolicy] = {}
  107. for room_id in room_ids:
  108. retention_policies[
  109. room_id
  110. ] = await storage.main.get_retention_policy_for_room(room_id)
  111. def allowed(event: EventBase) -> Optional[EventBase]:
  112. return _check_client_allowed_to_see_event(
  113. user_id=user_id,
  114. event=event,
  115. clock=storage.main.clock,
  116. filter_send_to_client=filter_send_to_client,
  117. sender_ignored=event.sender in ignore_list,
  118. always_include_ids=always_include_ids,
  119. retention_policy=retention_policies[room_id],
  120. state=event_id_to_state.get(event.event_id),
  121. is_peeking=is_peeking,
  122. sender_erased=erased_senders.get(event.sender, False),
  123. )
  124. # Check each event: gives an iterable of None or (a potentially modified)
  125. # EventBase.
  126. filtered_events = map(allowed, events)
  127. # Turn it into a list and remove None entries before returning.
  128. return [ev for ev in filtered_events if ev]
  129. async def filter_event_for_clients_with_state(
  130. store: DataStore,
  131. user_ids: Collection[str],
  132. event: EventBase,
  133. context: EventContext,
  134. is_peeking: bool = False,
  135. filter_send_to_client: bool = True,
  136. ) -> Collection[str]:
  137. """
  138. Checks to see if an event is visible to the users in the list at the time of
  139. the event.
  140. Note: This does *not* check if the sender of the event was erased.
  141. Args:
  142. store: databases
  143. user_ids: user_ids to be checked
  144. event: the event to be checked
  145. context: EventContext for the event to be checked
  146. is_peeking: Whether the users are peeking into the room, ie not
  147. currently joined
  148. filter_send_to_client: Whether we're checking an event that's going to be
  149. sent to a client. This might not always be the case since this function can
  150. also be called to check whether a user can see the state at a given point.
  151. Returns:
  152. Collection of user IDs for whom the event is visible
  153. """
  154. # None of the users should see the event if it is soft_failed
  155. if event.internal_metadata.is_soft_failed():
  156. return []
  157. # Fast path if we don't have any user IDs to check.
  158. if not user_ids:
  159. return ()
  160. # Make a set for all user IDs that haven't been filtered out by a check.
  161. allowed_user_ids = set(user_ids)
  162. # Only run some checks if these events aren't about to be sent to clients. This is
  163. # because, if this is not the case, we're probably only checking if the users can
  164. # see events in the room at that point in the DAG, and that shouldn't be decided
  165. # on those checks.
  166. if filter_send_to_client:
  167. ignored_by = await store.ignored_by(event.sender)
  168. retention_policy = await store.get_retention_policy_for_room(event.room_id)
  169. for user_id in user_ids:
  170. if (
  171. _check_filter_send_to_client(
  172. event,
  173. store.clock,
  174. retention_policy,
  175. sender_ignored=user_id in ignored_by,
  176. )
  177. == _CheckFilter.DENIED
  178. ):
  179. allowed_user_ids.discard(user_id)
  180. if event.internal_metadata.outlier:
  181. # Normally these can't be seen by clients, but we make an exception for
  182. # for out-of-band membership events (eg, incoming invites, or rejections of
  183. # said invite) for the user themselves.
  184. if event.type == EventTypes.Member and event.state_key in allowed_user_ids:
  185. logger.debug("Returning out-of-band-membership event %s", event)
  186. return {event.state_key}
  187. return set()
  188. # First we get just the history visibility in case its shared/world-readable
  189. # room.
  190. visibility_state_map = await _get_state_map(
  191. store, event, context, StateFilter.from_types([_HISTORY_VIS_KEY])
  192. )
  193. visibility = get_effective_room_visibility_from_state(visibility_state_map)
  194. if (
  195. _check_history_visibility(event, visibility, is_peeking=is_peeking)
  196. == _CheckVisibility.ALLOWED
  197. ):
  198. return allowed_user_ids
  199. # The history visibility isn't lax, so we now need to fetch the membership
  200. # events of all the users.
  201. filter_list = []
  202. for user_id in allowed_user_ids:
  203. filter_list.append((EventTypes.Member, user_id))
  204. filter_list.append((EventTypes.RoomHistoryVisibility, ""))
  205. state_filter = StateFilter.from_types(filter_list)
  206. state_map = await _get_state_map(store, event, context, state_filter)
  207. # Now we check whether the membership allows each user to see the event.
  208. return {
  209. user_id
  210. for user_id in allowed_user_ids
  211. if _check_membership(user_id, event, visibility, state_map, is_peeking).allowed
  212. }
  213. async def _get_state_map(
  214. store: DataStore, event: EventBase, context: EventContext, state_filter: StateFilter
  215. ) -> StateMap[EventBase]:
  216. """Helper function for getting a `StateMap[EventBase]` from an `EventContext`"""
  217. state_map = await context.get_prev_state_ids(state_filter)
  218. # Use events rather than event ids as content from the events are needed in
  219. # _check_visibility
  220. event_map = await store.get_events(state_map.values(), get_prev_content=False)
  221. updated_state_map = {}
  222. for state_key, event_id in state_map.items():
  223. state_event = event_map.get(event_id)
  224. if state_event:
  225. updated_state_map[state_key] = state_event
  226. if event.is_state():
  227. current_state_key = (event.type, event.state_key)
  228. # Add current event to updated_state_map, we need to do this here as it
  229. # may not have been persisted to the db yet
  230. updated_state_map[current_state_key] = event
  231. return updated_state_map
  232. def _check_client_allowed_to_see_event(
  233. user_id: str,
  234. event: EventBase,
  235. clock: Clock,
  236. filter_send_to_client: bool,
  237. is_peeking: bool,
  238. always_include_ids: FrozenSet[str],
  239. sender_ignored: bool,
  240. retention_policy: RetentionPolicy,
  241. state: Optional[StateMap[EventBase]],
  242. sender_erased: bool,
  243. ) -> Optional[EventBase]:
  244. """Check with the given user is allowed to see the given event
  245. See `filter_events_for_client` for details about args
  246. Args:
  247. user_id
  248. event
  249. clock
  250. filter_send_to_client
  251. is_peeking
  252. always_include_ids
  253. sender_ignored: Whether the user is ignoring the event sender
  254. retention_policy: The retention policy of the room
  255. state: The state at the event, unless its an outlier
  256. sender_erased: Whether the event sender has been marked as "erased"
  257. Returns:
  258. None if the user cannot see this event at all
  259. a redacted copy of the event if they can only see a redacted
  260. version
  261. the original event if they can see it as normal.
  262. """
  263. # Only run some checks if these events aren't about to be sent to clients. This is
  264. # because, if this is not the case, we're probably only checking if the users can
  265. # see events in the room at that point in the DAG, and that shouldn't be decided
  266. # on those checks.
  267. if filter_send_to_client:
  268. if (
  269. _check_filter_send_to_client(event, clock, retention_policy, sender_ignored)
  270. == _CheckFilter.DENIED
  271. ):
  272. filtered_event_logger.debug(
  273. "_check_client_allowed_to_see_event(event=%s): Filtered out event because `_check_filter_send_to_client` returned `_CheckFilter.DENIED`",
  274. event.event_id,
  275. )
  276. return None
  277. if event.event_id in always_include_ids:
  278. return event
  279. # we need to handle outliers separately, since we don't have the room state.
  280. if event.internal_metadata.outlier:
  281. # Normally these can't be seen by clients, but we make an exception for
  282. # for out-of-band membership events (eg, incoming invites, or rejections of
  283. # said invite) for the user themselves.
  284. if event.type == EventTypes.Member and event.state_key == user_id:
  285. logger.debug(
  286. "_check_client_allowed_to_see_event(event=%s): Returning out-of-band-membership event %s",
  287. event.event_id,
  288. event,
  289. )
  290. return event
  291. filtered_event_logger.debug(
  292. "_check_client_allowed_to_see_event(event=%s): Filtered out event because it's an outlier",
  293. event.event_id,
  294. )
  295. return None
  296. if state is None:
  297. raise Exception("Missing state for non-outlier event")
  298. # get the room_visibility at the time of the event.
  299. visibility = get_effective_room_visibility_from_state(state)
  300. # Check if the room has lax history visibility, allowing us to skip
  301. # membership checks.
  302. #
  303. # We can only do this check if the sender has *not* been erased, as if they
  304. # have we need to check the user's membership.
  305. if (
  306. not sender_erased
  307. and _check_history_visibility(event, visibility, is_peeking)
  308. == _CheckVisibility.ALLOWED
  309. ):
  310. return event
  311. membership_result = _check_membership(user_id, event, visibility, state, is_peeking)
  312. if not membership_result.allowed:
  313. filtered_event_logger.debug(
  314. "_check_client_allowed_to_see_event(event=%s): Filtered out event because the user can't see the event because of their membership, membership_result.allowed=%s membership_result.joined=%s",
  315. event.event_id,
  316. membership_result.allowed,
  317. membership_result.joined,
  318. )
  319. return None
  320. # If the sender has been erased and the user was not joined at the time, we
  321. # must only return the redacted form.
  322. if sender_erased and not membership_result.joined:
  323. filtered_event_logger.debug(
  324. "_check_client_allowed_to_see_event(event=%s): Returning pruned event because `sender_erased` and the user was not joined at the time",
  325. event.event_id,
  326. )
  327. event = prune_event(event)
  328. return event
  329. @attr.s(frozen=True, slots=True, auto_attribs=True)
  330. class _CheckMembershipReturn:
  331. "Return value of _check_membership"
  332. allowed: bool
  333. joined: bool
  334. def _check_membership(
  335. user_id: str,
  336. event: EventBase,
  337. visibility: str,
  338. state: StateMap[EventBase],
  339. is_peeking: bool,
  340. ) -> _CheckMembershipReturn:
  341. """Check whether the user can see the event due to their membership
  342. Returns:
  343. True if they can, False if they can't, plus the membership of the user
  344. at the event.
  345. """
  346. # If the event is the user's own membership event, use the 'most joined'
  347. # membership
  348. membership = None
  349. if event.type == EventTypes.Member and event.state_key == user_id:
  350. membership = event.content.get("membership", None)
  351. if membership not in MEMBERSHIP_PRIORITY:
  352. membership = "leave"
  353. prev_content = event.unsigned.get("prev_content", {})
  354. prev_membership = prev_content.get("membership", None)
  355. if prev_membership not in MEMBERSHIP_PRIORITY:
  356. prev_membership = "leave"
  357. # Always allow the user to see their own leave events, otherwise
  358. # they won't see the room disappear if they reject the invite
  359. #
  360. # (Note this doesn't work for out-of-band invite rejections, which don't
  361. # have prev_state populated. They are handled above in the outlier code.)
  362. if membership == "leave" and (
  363. prev_membership == "join" or prev_membership == "invite"
  364. ):
  365. return _CheckMembershipReturn(True, membership == Membership.JOIN)
  366. new_priority = MEMBERSHIP_PRIORITY.index(membership)
  367. old_priority = MEMBERSHIP_PRIORITY.index(prev_membership)
  368. if old_priority < new_priority:
  369. membership = prev_membership
  370. # otherwise, get the user's membership at the time of the event.
  371. if membership is None:
  372. membership_event = state.get((EventTypes.Member, user_id), None)
  373. if membership_event:
  374. membership = membership_event.membership
  375. # if the user was a member of the room at the time of the event,
  376. # they can see it.
  377. if membership == Membership.JOIN:
  378. return _CheckMembershipReturn(True, True)
  379. # otherwise, it depends on the room visibility.
  380. if visibility == HistoryVisibility.JOINED:
  381. # we weren't a member at the time of the event, so we can't
  382. # see this event.
  383. return _CheckMembershipReturn(False, False)
  384. elif visibility == HistoryVisibility.INVITED:
  385. # user can also see the event if they were *invited* at the time
  386. # of the event.
  387. return _CheckMembershipReturn(membership == Membership.INVITE, False)
  388. elif visibility == HistoryVisibility.SHARED and is_peeking:
  389. # if the visibility is shared, users cannot see the event unless
  390. # they have *subsequently* joined the room (or were members at the
  391. # time, of course)
  392. #
  393. # XXX: if the user has subsequently joined and then left again,
  394. # ideally we would share history up to the point they left. But
  395. # we don't know when they left. We just treat it as though they
  396. # never joined, and restrict access.
  397. return _CheckMembershipReturn(False, False)
  398. # The visibility is either shared or world_readable, and the user was
  399. # not a member at the time. We allow it.
  400. return _CheckMembershipReturn(True, False)
  401. class _CheckFilter(Enum):
  402. MAYBE_ALLOWED = auto()
  403. DENIED = auto()
  404. def _check_filter_send_to_client(
  405. event: EventBase,
  406. clock: Clock,
  407. retention_policy: RetentionPolicy,
  408. sender_ignored: bool,
  409. ) -> _CheckFilter:
  410. """Apply checks for sending events to client
  411. Returns:
  412. True if might be allowed to be sent to clients, False if definitely not.
  413. """
  414. if event.type == EventTypes.Dummy:
  415. return _CheckFilter.DENIED
  416. if not event.is_state() and sender_ignored:
  417. return _CheckFilter.DENIED
  418. # Until MSC2261 has landed we can't redact malicious alias events, so for
  419. # now we temporarily filter out m.room.aliases entirely to mitigate
  420. # abuse, while we spec a better solution to advertising aliases
  421. # on rooms.
  422. if event.type == EventTypes.Aliases:
  423. return _CheckFilter.DENIED
  424. # Don't try to apply the room's retention policy if the event is a state
  425. # event, as MSC1763 states that retention is only considered for non-state
  426. # events.
  427. if not event.is_state():
  428. max_lifetime = retention_policy.max_lifetime
  429. if max_lifetime is not None:
  430. oldest_allowed_ts = clock.time_msec() - max_lifetime
  431. if event.origin_server_ts < oldest_allowed_ts:
  432. return _CheckFilter.DENIED
  433. return _CheckFilter.MAYBE_ALLOWED
  434. class _CheckVisibility(Enum):
  435. ALLOWED = auto()
  436. MAYBE_DENIED = auto()
  437. def _check_history_visibility(
  438. event: EventBase, visibility: str, is_peeking: bool
  439. ) -> _CheckVisibility:
  440. """Check if event is allowed to be seen due to lax history visibility.
  441. Returns:
  442. True if user can definitely see the event, False if maybe not.
  443. """
  444. # Always allow history visibility events on boundaries. This is done
  445. # by setting the effective visibility to the least restrictive
  446. # of the old vs new.
  447. if event.type == EventTypes.RoomHistoryVisibility:
  448. prev_content = event.unsigned.get("prev_content", {})
  449. prev_visibility = prev_content.get("history_visibility", None)
  450. if prev_visibility not in VISIBILITY_PRIORITY:
  451. prev_visibility = HistoryVisibility.SHARED
  452. new_priority = VISIBILITY_PRIORITY.index(visibility)
  453. old_priority = VISIBILITY_PRIORITY.index(prev_visibility)
  454. if old_priority < new_priority:
  455. visibility = prev_visibility
  456. if visibility == HistoryVisibility.SHARED and not is_peeking:
  457. return _CheckVisibility.ALLOWED
  458. elif visibility == HistoryVisibility.WORLD_READABLE:
  459. return _CheckVisibility.ALLOWED
  460. return _CheckVisibility.MAYBE_DENIED
  461. def get_effective_room_visibility_from_state(state: StateMap[EventBase]) -> str:
  462. """Get the actual history vis, from a state map including the history_visibility event
  463. Handles missing and invalid history visibility events.
  464. """
  465. visibility_event = state.get(_HISTORY_VIS_KEY, None)
  466. if not visibility_event:
  467. return HistoryVisibility.SHARED
  468. visibility = visibility_event.content.get(
  469. "history_visibility", HistoryVisibility.SHARED
  470. )
  471. if visibility not in VISIBILITY_PRIORITY:
  472. visibility = HistoryVisibility.SHARED
  473. return visibility
  474. async def filter_events_for_server(
  475. storage: StorageControllers,
  476. target_server_name: str,
  477. local_server_name: str,
  478. events: Sequence[EventBase],
  479. *,
  480. redact: bool,
  481. filter_out_erased_senders: bool,
  482. filter_out_remote_partial_state_events: bool,
  483. ) -> List[EventBase]:
  484. """Filter a list of events based on whether the target server is allowed to
  485. see them.
  486. For a fully stated room, the target server is allowed to see an event E if:
  487. - the state at E has world readable or shared history vis, OR
  488. - the state at E says that the target server is in the room.
  489. For a partially stated room, the target server is allowed to see E if:
  490. - E was created by this homeserver, AND:
  491. - the partial state at E has world readable or shared history vis, OR
  492. - the partial state at E says that the target server is in the room.
  493. TODO: state before or state after?
  494. Args:
  495. storage
  496. target_server_name
  497. local_server_name
  498. events
  499. redact: Controls what to do with events which have been filtered out.
  500. If True, include their redacted forms; if False, omit them entirely.
  501. filter_out_erased_senders: If true, also filter out events whose sender has been
  502. erased. This is used e.g. during pagination to decide whether to
  503. backfill or not.
  504. filter_out_remote_partial_state_events: If True, also filter out events in
  505. partial state rooms created by other homeservers.
  506. Returns
  507. The filtered events.
  508. """
  509. def is_sender_erased(event: EventBase, erased_senders: Mapping[str, bool]) -> bool:
  510. if erased_senders and erased_senders[event.sender]:
  511. logger.info("Sender of %s has been erased, redacting", event.event_id)
  512. return True
  513. return False
  514. def check_event_is_visible(
  515. visibility: str, memberships: StateMap[EventBase]
  516. ) -> bool:
  517. if visibility not in (HistoryVisibility.INVITED, HistoryVisibility.JOINED):
  518. return True
  519. # We now loop through all membership events looking for
  520. # membership states for the requesting server to determine
  521. # if the server is either in the room or has been invited
  522. # into the room.
  523. for ev in memberships.values():
  524. assert get_domain_from_id(ev.state_key) == target_server_name
  525. memtype = ev.membership
  526. if memtype == Membership.JOIN:
  527. return True
  528. elif memtype == Membership.INVITE:
  529. if visibility == HistoryVisibility.INVITED:
  530. return True
  531. # server has no users in the room: redact
  532. return False
  533. if filter_out_erased_senders:
  534. erased_senders = await storage.main.are_users_erased(e.sender for e in events)
  535. else:
  536. # We don't want to check whether users are erased, which is equivalent
  537. # to no users having been erased.
  538. erased_senders = {}
  539. # Filter out non-local events when we are in the middle of a partial join, since our servers
  540. # list can be out of date and we could leak events to servers not in the room anymore.
  541. # This can also be true for local events but we consider it to be an acceptable risk.
  542. # We do this check as a first step and before retrieving membership events because
  543. # otherwise a room could be fully joined after we retrieve those, which would then bypass
  544. # this check but would base the filtering on an outdated view of the membership events.
  545. partial_state_invisible_event_ids: Set[str] = set()
  546. if filter_out_remote_partial_state_events:
  547. for e in events:
  548. sender_domain = get_domain_from_id(e.sender)
  549. if (
  550. sender_domain != local_server_name
  551. and await storage.main.is_partial_state_room(e.room_id)
  552. ):
  553. partial_state_invisible_event_ids.add(e.event_id)
  554. # Let's check to see if all the events have a history visibility
  555. # of "shared" or "world_readable". If that's the case then we don't
  556. # need to check membership (as we know the server is in the room).
  557. event_to_history_vis = await _event_to_history_vis(storage, events)
  558. # for any with restricted vis, we also need the memberships
  559. event_to_memberships = await _event_to_memberships(
  560. storage,
  561. [
  562. e
  563. for e in events
  564. if event_to_history_vis[e.event_id]
  565. not in (HistoryVisibility.SHARED, HistoryVisibility.WORLD_READABLE)
  566. ],
  567. target_server_name,
  568. )
  569. def include_event_in_output(e: EventBase) -> bool:
  570. erased = is_sender_erased(e, erased_senders)
  571. visible = check_event_is_visible(
  572. event_to_history_vis[e.event_id], event_to_memberships.get(e.event_id, {})
  573. )
  574. if e.event_id in partial_state_invisible_event_ids:
  575. visible = False
  576. return visible and not erased
  577. to_return = []
  578. for e in events:
  579. if include_event_in_output(e):
  580. to_return.append(e)
  581. elif redact:
  582. to_return.append(prune_event(e))
  583. return to_return
  584. async def _event_to_history_vis(
  585. storage: StorageControllers, events: Collection[EventBase]
  586. ) -> Dict[str, str]:
  587. """Get the history visibility at each of the given events
  588. Returns a map from event id to history_visibility setting
  589. """
  590. # outliers get special treatment here. We don't have the state at that point in the
  591. # room (and attempting to look it up will raise an exception), so all we can really
  592. # do is assume that the requesting server is allowed to see the event. That's
  593. # equivalent to there not being a history_visibility event, so we just exclude
  594. # any outliers from the query.
  595. event_to_state_ids = await storage.state.get_state_ids_for_events(
  596. frozenset(e.event_id for e in events if not e.internal_metadata.is_outlier()),
  597. state_filter=StateFilter.from_types(types=(_HISTORY_VIS_KEY,)),
  598. )
  599. visibility_ids = {
  600. vis_event_id
  601. for vis_event_id in (
  602. state_ids.get(_HISTORY_VIS_KEY) for state_ids in event_to_state_ids.values()
  603. )
  604. if vis_event_id
  605. }
  606. vis_events = await storage.main.get_events(visibility_ids)
  607. result: Dict[str, str] = {}
  608. for event in events:
  609. vis = HistoryVisibility.SHARED
  610. state_ids = event_to_state_ids.get(event.event_id)
  611. # if we didn't find any state for this event, it's an outlier, and we assume
  612. # it's open
  613. visibility_id = None
  614. if state_ids:
  615. visibility_id = state_ids.get(_HISTORY_VIS_KEY)
  616. if visibility_id:
  617. vis_event = vis_events[visibility_id]
  618. vis = vis_event.content.get("history_visibility", HistoryVisibility.SHARED)
  619. assert isinstance(vis, str)
  620. result[event.event_id] = vis
  621. return result
  622. async def _event_to_memberships(
  623. storage: StorageControllers, events: Collection[EventBase], server_name: str
  624. ) -> Dict[str, StateMap[EventBase]]:
  625. """Get the remote membership list at each of the given events
  626. Returns a map from event id to state map, which will contain only membership events
  627. for the given server.
  628. """
  629. if not events:
  630. return {}
  631. # for each event, get the event_ids of the membership state at those events.
  632. #
  633. # TODO: this means that we request the entire membership list. If there are only
  634. # one or two users on this server, and the room is huge, this is very wasteful
  635. # (it means more db work, and churns the *stateGroupMembersCache*).
  636. # It might be that we could extend StateFilter to specify "give me keys matching
  637. # *:<server_name>", to avoid this.
  638. event_to_state_ids = await storage.state.get_state_ids_for_events(
  639. frozenset(e.event_id for e in events),
  640. state_filter=StateFilter.from_types(types=((EventTypes.Member, None),)),
  641. )
  642. # We only want to pull out member events that correspond to the
  643. # server's domain.
  644. #
  645. # event_to_state_ids contains lots of duplicates, so it turns out to be
  646. # cheaper to build a complete event_id => (type, state_key) dict, and then
  647. # filter out the ones we don't want
  648. #
  649. event_id_to_state_key = {
  650. event_id: key
  651. for key_to_eid in event_to_state_ids.values()
  652. for key, event_id in key_to_eid.items()
  653. }
  654. def include(state_key: str) -> bool:
  655. # we avoid using get_domain_from_id here for efficiency.
  656. idx = state_key.find(":")
  657. if idx == -1:
  658. return False
  659. return state_key[idx + 1 :] == server_name
  660. event_map = await storage.main.get_events(
  661. [
  662. e_id
  663. for e_id, (_, state_key) in event_id_to_state_key.items()
  664. if include(state_key)
  665. ]
  666. )
  667. return {
  668. e_id: {
  669. key: event_map[inner_e_id]
  670. for key, inner_e_id in key_to_eid.items()
  671. if inner_e_id in event_map
  672. }
  673. for e_id, key_to_eid in event_to_state_ids.items()
  674. }