visibility.py 26 KB

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