visibility.py 27 KB

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