visibility.py 26 KB

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