visibility.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 typing import Collection, Dict, FrozenSet, List, Optional, Tuple
  17. from typing_extensions import Final
  18. from synapse.api.constants import EventTypes, HistoryVisibility, Membership
  19. from synapse.events import EventBase
  20. from synapse.events.utils import prune_event
  21. from synapse.storage.controllers import StorageControllers
  22. from synapse.storage.state import StateFilter
  23. from synapse.types import RetentionPolicy, StateMap, get_domain_from_id
  24. logger = logging.getLogger(__name__)
  25. VISIBILITY_PRIORITY = (
  26. HistoryVisibility.WORLD_READABLE,
  27. HistoryVisibility.SHARED,
  28. HistoryVisibility.INVITED,
  29. HistoryVisibility.JOINED,
  30. )
  31. MEMBERSHIP_PRIORITY = (
  32. Membership.JOIN,
  33. Membership.INVITE,
  34. Membership.KNOCK,
  35. Membership.LEAVE,
  36. Membership.BAN,
  37. )
  38. _HISTORY_VIS_KEY: Final[Tuple[str, str]] = (EventTypes.RoomHistoryVisibility, "")
  39. async def filter_events_for_client(
  40. storage: StorageControllers,
  41. user_id: str,
  42. events: List[EventBase],
  43. is_peeking: bool = False,
  44. always_include_ids: FrozenSet[str] = frozenset(),
  45. filter_send_to_client: bool = True,
  46. ) -> List[EventBase]:
  47. """
  48. Check which events a user is allowed to see. If the user can see the event but its
  49. sender asked for their data to be erased, prune the content of the event.
  50. Args:
  51. storage
  52. user_id: user id to be checked
  53. events: sequence of events to be checked
  54. is_peeking: should be True if:
  55. * the user is not currently a member of the room, and:
  56. * the user has not been a member of the room since the given
  57. events
  58. always_include_ids: set of event ids to specifically
  59. include (unless sender is ignored)
  60. filter_send_to_client: Whether we're checking an event that's going to be
  61. sent to a client. This might not always be the case since this function can
  62. also be called to check whether a user can see the state at a given point.
  63. Returns:
  64. The filtered events.
  65. """
  66. # Filter out events that have been soft failed so that we don't relay them
  67. # to clients.
  68. events = [e for e in events if not e.internal_metadata.is_soft_failed()]
  69. types = (_HISTORY_VIS_KEY, (EventTypes.Member, user_id))
  70. # we exclude outliers at this point, and then handle them separately later
  71. event_id_to_state = await storage.state.get_state_for_events(
  72. frozenset(e.event_id for e in events if not e.internal_metadata.outlier),
  73. state_filter=StateFilter.from_types(types),
  74. )
  75. # Get the users who are ignored by the requesting user.
  76. ignore_list = await storage.main.ignored_users(user_id)
  77. erased_senders = await storage.main.are_users_erased(e.sender for e in events)
  78. if filter_send_to_client:
  79. room_ids = {e.room_id for e in events}
  80. retention_policies: Dict[str, RetentionPolicy] = {}
  81. for room_id in room_ids:
  82. retention_policies[
  83. room_id
  84. ] = await storage.main.get_retention_policy_for_room(room_id)
  85. def allowed(event: EventBase) -> Optional[EventBase]:
  86. """
  87. Args:
  88. event: event to check
  89. Returns:
  90. None if the user cannot see this event at all
  91. a redacted copy of the event if they can only see a redacted
  92. version
  93. the original event if they can see it as normal.
  94. """
  95. # Only run some checks if these events aren't about to be sent to clients. This is
  96. # because, if this is not the case, we're probably only checking if the users can
  97. # see events in the room at that point in the DAG, and that shouldn't be decided
  98. # on those checks.
  99. if filter_send_to_client:
  100. if event.type == EventTypes.Dummy:
  101. return None
  102. if not event.is_state() and event.sender in ignore_list:
  103. return None
  104. # Until MSC2261 has landed we can't redact malicious alias events, so for
  105. # now we temporarily filter out m.room.aliases entirely to mitigate
  106. # abuse, while we spec a better solution to advertising aliases
  107. # on rooms.
  108. if event.type == EventTypes.Aliases:
  109. return None
  110. # Don't try to apply the room's retention policy if the event is a state
  111. # event, as MSC1763 states that retention is only considered for non-state
  112. # events.
  113. if not event.is_state():
  114. retention_policy = retention_policies[event.room_id]
  115. max_lifetime = retention_policy.max_lifetime
  116. if max_lifetime is not None:
  117. oldest_allowed_ts = storage.main.clock.time_msec() - max_lifetime
  118. if event.origin_server_ts < oldest_allowed_ts:
  119. return None
  120. if event.event_id in always_include_ids:
  121. return event
  122. # we need to handle outliers separately, since we don't have the room state.
  123. if event.internal_metadata.outlier:
  124. # Normally these can't be seen by clients, but we make an exception for
  125. # for out-of-band membership events (eg, incoming invites, or rejections of
  126. # said invite) for the user themselves.
  127. if event.type == EventTypes.Member and event.state_key == user_id:
  128. logger.debug("Returning out-of-band-membership event %s", event)
  129. return event
  130. return None
  131. state = event_id_to_state[event.event_id]
  132. # get the room_visibility at the time of the event.
  133. visibility = get_effective_room_visibility_from_state(state)
  134. # Always allow history visibility events on boundaries. This is done
  135. # by setting the effective visibility to the least restrictive
  136. # of the old vs new.
  137. if event.type == EventTypes.RoomHistoryVisibility:
  138. prev_content = event.unsigned.get("prev_content", {})
  139. prev_visibility = prev_content.get("history_visibility", None)
  140. if prev_visibility not in VISIBILITY_PRIORITY:
  141. prev_visibility = HistoryVisibility.SHARED
  142. new_priority = VISIBILITY_PRIORITY.index(visibility)
  143. old_priority = VISIBILITY_PRIORITY.index(prev_visibility)
  144. if old_priority < new_priority:
  145. visibility = prev_visibility
  146. # likewise, if the event is the user's own membership event, use
  147. # the 'most joined' membership
  148. membership = None
  149. if event.type == EventTypes.Member and event.state_key == user_id:
  150. membership = event.content.get("membership", None)
  151. if membership not in MEMBERSHIP_PRIORITY:
  152. membership = "leave"
  153. prev_content = event.unsigned.get("prev_content", {})
  154. prev_membership = prev_content.get("membership", None)
  155. if prev_membership not in MEMBERSHIP_PRIORITY:
  156. prev_membership = "leave"
  157. # Always allow the user to see their own leave events, otherwise
  158. # they won't see the room disappear if they reject the invite
  159. #
  160. # (Note this doesn't work for out-of-band invite rejections, which don't
  161. # have prev_state populated. They are handled above in the outlier code.)
  162. if membership == "leave" and (
  163. prev_membership == "join" or prev_membership == "invite"
  164. ):
  165. return event
  166. new_priority = MEMBERSHIP_PRIORITY.index(membership)
  167. old_priority = MEMBERSHIP_PRIORITY.index(prev_membership)
  168. if old_priority < new_priority:
  169. membership = prev_membership
  170. # otherwise, get the user's membership at the time of the event.
  171. if membership is None:
  172. membership_event = state.get((EventTypes.Member, user_id), None)
  173. if membership_event:
  174. membership = membership_event.membership
  175. # if the user was a member of the room at the time of the event,
  176. # they can see it.
  177. if membership == Membership.JOIN:
  178. return event
  179. # otherwise, it depends on the room visibility.
  180. if visibility == HistoryVisibility.JOINED:
  181. # we weren't a member at the time of the event, so we can't
  182. # see this event.
  183. return None
  184. elif visibility == HistoryVisibility.INVITED:
  185. # user can also see the event if they were *invited* at the time
  186. # of the event.
  187. return event if membership == Membership.INVITE else None
  188. elif visibility == HistoryVisibility.SHARED and is_peeking:
  189. # if the visibility is shared, users cannot see the event unless
  190. # they have *subsequently* joined the room (or were members at the
  191. # time, of course)
  192. #
  193. # XXX: if the user has subsequently joined and then left again,
  194. # ideally we would share history up to the point they left. But
  195. # we don't know when they left. We just treat it as though they
  196. # never joined, and restrict access.
  197. return None
  198. # the visibility is either shared or world_readable, and the user was
  199. # not a member at the time. We allow it, provided the original sender
  200. # has not requested their data to be erased, in which case, we return
  201. # a redacted version.
  202. if erased_senders[event.sender]:
  203. return prune_event(event)
  204. return event
  205. # Check each event: gives an iterable of None or (a potentially modified)
  206. # EventBase.
  207. filtered_events = map(allowed, events)
  208. # Turn it into a list and remove None entries before returning.
  209. return [ev for ev in filtered_events if ev]
  210. def get_effective_room_visibility_from_state(state: StateMap[EventBase]) -> str:
  211. """Get the actual history vis, from a state map including the history_visibility event
  212. Handles missing and invalid history visibility events.
  213. """
  214. visibility_event = state.get(_HISTORY_VIS_KEY, None)
  215. if not visibility_event:
  216. return HistoryVisibility.SHARED
  217. visibility = visibility_event.content.get(
  218. "history_visibility", HistoryVisibility.SHARED
  219. )
  220. if visibility not in VISIBILITY_PRIORITY:
  221. visibility = HistoryVisibility.SHARED
  222. return visibility
  223. async def filter_events_for_server(
  224. storage: StorageControllers,
  225. server_name: str,
  226. events: List[EventBase],
  227. redact: bool = True,
  228. check_history_visibility_only: bool = False,
  229. ) -> List[EventBase]:
  230. """Filter a list of events based on whether given server is allowed to
  231. see them.
  232. Args:
  233. storage
  234. server_name
  235. events
  236. redact: Whether to return a redacted version of the event, or
  237. to filter them out entirely.
  238. check_history_visibility_only: Whether to only check the
  239. history visibility, rather than things like if the sender has been
  240. erased. This is used e.g. during pagination to decide whether to
  241. backfill or not.
  242. Returns
  243. The filtered events.
  244. """
  245. def is_sender_erased(event: EventBase, erased_senders: Dict[str, bool]) -> bool:
  246. if erased_senders and erased_senders[event.sender]:
  247. logger.info("Sender of %s has been erased, redacting", event.event_id)
  248. return True
  249. return False
  250. def check_event_is_visible(
  251. visibility: str, memberships: StateMap[EventBase]
  252. ) -> bool:
  253. if visibility not in (HistoryVisibility.INVITED, HistoryVisibility.JOINED):
  254. return True
  255. # We now loop through all membership events looking for
  256. # membership states for the requesting server to determine
  257. # if the server is either in the room or has been invited
  258. # into the room.
  259. for ev in memberships.values():
  260. assert get_domain_from_id(ev.state_key) == server_name
  261. memtype = ev.membership
  262. if memtype == Membership.JOIN:
  263. return True
  264. elif memtype == Membership.INVITE:
  265. if visibility == HistoryVisibility.INVITED:
  266. return True
  267. # server has no users in the room: redact
  268. return False
  269. if not check_history_visibility_only:
  270. erased_senders = await storage.main.are_users_erased(e.sender for e in events)
  271. else:
  272. # We don't want to check whether users are erased, which is equivalent
  273. # to no users having been erased.
  274. erased_senders = {}
  275. # Let's check to see if all the events have a history visibility
  276. # of "shared" or "world_readable". If that's the case then we don't
  277. # need to check membership (as we know the server is in the room).
  278. event_to_history_vis = await _event_to_history_vis(storage, events)
  279. # for any with restricted vis, we also need the memberships
  280. event_to_memberships = await _event_to_memberships(
  281. storage,
  282. [
  283. e
  284. for e in events
  285. if event_to_history_vis[e.event_id]
  286. not in (HistoryVisibility.SHARED, HistoryVisibility.WORLD_READABLE)
  287. ],
  288. server_name,
  289. )
  290. to_return = []
  291. for e in events:
  292. erased = is_sender_erased(e, erased_senders)
  293. visible = check_event_is_visible(
  294. event_to_history_vis[e.event_id], event_to_memberships.get(e.event_id, {})
  295. )
  296. if visible and not erased:
  297. to_return.append(e)
  298. elif redact:
  299. to_return.append(prune_event(e))
  300. return to_return
  301. async def _event_to_history_vis(
  302. storage: StorageControllers, events: Collection[EventBase]
  303. ) -> Dict[str, str]:
  304. """Get the history visibility at each of the given events
  305. Returns a map from event id to history_visibility setting
  306. """
  307. # outliers get special treatment here. We don't have the state at that point in the
  308. # room (and attempting to look it up will raise an exception), so all we can really
  309. # do is assume that the requesting server is allowed to see the event. That's
  310. # equivalent to there not being a history_visibility event, so we just exclude
  311. # any outliers from the query.
  312. event_to_state_ids = await storage.state.get_state_ids_for_events(
  313. frozenset(e.event_id for e in events if not e.internal_metadata.is_outlier()),
  314. state_filter=StateFilter.from_types(types=(_HISTORY_VIS_KEY,)),
  315. )
  316. visibility_ids = {
  317. vis_event_id
  318. for vis_event_id in (
  319. state_ids.get(_HISTORY_VIS_KEY) for state_ids in event_to_state_ids.values()
  320. )
  321. if vis_event_id
  322. }
  323. vis_events = await storage.main.get_events(visibility_ids)
  324. result: Dict[str, str] = {}
  325. for event in events:
  326. vis = HistoryVisibility.SHARED
  327. state_ids = event_to_state_ids.get(event.event_id)
  328. # if we didn't find any state for this event, it's an outlier, and we assume
  329. # it's open
  330. visibility_id = None
  331. if state_ids:
  332. visibility_id = state_ids.get(_HISTORY_VIS_KEY)
  333. if visibility_id:
  334. vis_event = vis_events[visibility_id]
  335. vis = vis_event.content.get("history_visibility", HistoryVisibility.SHARED)
  336. assert isinstance(vis, str)
  337. result[event.event_id] = vis
  338. return result
  339. async def _event_to_memberships(
  340. storage: StorageControllers, events: Collection[EventBase], server_name: str
  341. ) -> Dict[str, StateMap[EventBase]]:
  342. """Get the remote membership list at each of the given events
  343. Returns a map from event id to state map, which will contain only membership events
  344. for the given server.
  345. """
  346. if not events:
  347. return {}
  348. # for each event, get the event_ids of the membership state at those events.
  349. #
  350. # TODO: this means that we request the entire membership list. If there are only
  351. # one or two users on this server, and the room is huge, this is very wasteful
  352. # (it means more db work, and churns the *stateGroupMembersCache*).
  353. # It might be that we could extend StateFilter to specify "give me keys matching
  354. # *:<server_name>", to avoid this.
  355. event_to_state_ids = await storage.state.get_state_ids_for_events(
  356. frozenset(e.event_id for e in events),
  357. state_filter=StateFilter.from_types(types=((EventTypes.Member, None),)),
  358. )
  359. # We only want to pull out member events that correspond to the
  360. # server's domain.
  361. #
  362. # event_to_state_ids contains lots of duplicates, so it turns out to be
  363. # cheaper to build a complete event_id => (type, state_key) dict, and then
  364. # filter out the ones we don't want
  365. #
  366. event_id_to_state_key = {
  367. event_id: key
  368. for key_to_eid in event_to_state_ids.values()
  369. for key, event_id in key_to_eid.items()
  370. }
  371. def include(state_key: str) -> bool:
  372. # we avoid using get_domain_from_id here for efficiency.
  373. idx = state_key.find(":")
  374. if idx == -1:
  375. return False
  376. return state_key[idx + 1 :] == server_name
  377. event_map = await storage.main.get_events(
  378. [
  379. e_id
  380. for e_id, (_, state_key) in event_id_to_state_key.items()
  381. if include(state_key)
  382. ]
  383. )
  384. return {
  385. e_id: {
  386. key: event_map[inner_e_id]
  387. for key, inner_e_id in key_to_eid.items()
  388. if inner_e_id in event_map
  389. }
  390. for e_id, key_to_eid in event_to_state_ids.items()
  391. }