visibility.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 import Storage
  22. from synapse.storage.state import StateFilter
  23. from synapse.types import 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: Storage,
  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 = {}
  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.get("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_event = state.get(_HISTORY_VIS_KEY, None)
  134. if visibility_event:
  135. visibility = visibility_event.content.get(
  136. "history_visibility", HistoryVisibility.SHARED
  137. )
  138. else:
  139. visibility = HistoryVisibility.SHARED
  140. if visibility not in VISIBILITY_PRIORITY:
  141. visibility = HistoryVisibility.SHARED
  142. # Always allow history visibility events on boundaries. This is done
  143. # by setting the effective visibility to the least restrictive
  144. # of the old vs new.
  145. if event.type == EventTypes.RoomHistoryVisibility:
  146. prev_content = event.unsigned.get("prev_content", {})
  147. prev_visibility = prev_content.get("history_visibility", None)
  148. if prev_visibility not in VISIBILITY_PRIORITY:
  149. prev_visibility = HistoryVisibility.SHARED
  150. new_priority = VISIBILITY_PRIORITY.index(visibility)
  151. old_priority = VISIBILITY_PRIORITY.index(prev_visibility)
  152. if old_priority < new_priority:
  153. visibility = prev_visibility
  154. # likewise, if the event is the user's own membership event, use
  155. # the 'most joined' membership
  156. membership = None
  157. if event.type == EventTypes.Member and event.state_key == user_id:
  158. membership = event.content.get("membership", None)
  159. if membership not in MEMBERSHIP_PRIORITY:
  160. membership = "leave"
  161. prev_content = event.unsigned.get("prev_content", {})
  162. prev_membership = prev_content.get("membership", None)
  163. if prev_membership not in MEMBERSHIP_PRIORITY:
  164. prev_membership = "leave"
  165. # Always allow the user to see their own leave events, otherwise
  166. # they won't see the room disappear if they reject the invite
  167. #
  168. # (Note this doesn't work for out-of-band invite rejections, which don't
  169. # have prev_state populated. They are handled above in the outlier code.)
  170. if membership == "leave" and (
  171. prev_membership == "join" or prev_membership == "invite"
  172. ):
  173. return event
  174. new_priority = MEMBERSHIP_PRIORITY.index(membership)
  175. old_priority = MEMBERSHIP_PRIORITY.index(prev_membership)
  176. if old_priority < new_priority:
  177. membership = prev_membership
  178. # otherwise, get the user's membership at the time of the event.
  179. if membership is None:
  180. membership_event = state.get((EventTypes.Member, user_id), None)
  181. if membership_event:
  182. membership = membership_event.membership
  183. # if the user was a member of the room at the time of the event,
  184. # they can see it.
  185. if membership == Membership.JOIN:
  186. return event
  187. # otherwise, it depends on the room visibility.
  188. if visibility == HistoryVisibility.JOINED:
  189. # we weren't a member at the time of the event, so we can't
  190. # see this event.
  191. return None
  192. elif visibility == HistoryVisibility.INVITED:
  193. # user can also see the event if they were *invited* at the time
  194. # of the event.
  195. return event if membership == Membership.INVITE else None
  196. elif visibility == HistoryVisibility.SHARED and is_peeking:
  197. # if the visibility is shared, users cannot see the event unless
  198. # they have *subsequently* joined the room (or were members at the
  199. # time, of course)
  200. #
  201. # XXX: if the user has subsequently joined and then left again,
  202. # ideally we would share history up to the point they left. But
  203. # we don't know when they left. We just treat it as though they
  204. # never joined, and restrict access.
  205. return None
  206. # the visibility is either shared or world_readable, and the user was
  207. # not a member at the time. We allow it, provided the original sender
  208. # has not requested their data to be erased, in which case, we return
  209. # a redacted version.
  210. if erased_senders[event.sender]:
  211. return prune_event(event)
  212. return event
  213. # Check each event: gives an iterable of None or (a potentially modified)
  214. # EventBase.
  215. filtered_events = map(allowed, events)
  216. # Turn it into a list and remove None entries before returning.
  217. return [ev for ev in filtered_events if ev]
  218. async def filter_events_for_server(
  219. storage: Storage,
  220. server_name: str,
  221. events: List[EventBase],
  222. redact: bool = True,
  223. check_history_visibility_only: bool = False,
  224. ) -> List[EventBase]:
  225. """Filter a list of events based on whether given server is allowed to
  226. see them.
  227. Args:
  228. storage
  229. server_name
  230. events
  231. redact: Whether to return a redacted version of the event, or
  232. to filter them out entirely.
  233. check_history_visibility_only: Whether to only check the
  234. history visibility, rather than things like if the sender has been
  235. erased. This is used e.g. during pagination to decide whether to
  236. backfill or not.
  237. Returns
  238. The filtered events.
  239. """
  240. def is_sender_erased(event: EventBase, erased_senders: Dict[str, bool]) -> bool:
  241. if erased_senders and erased_senders[event.sender]:
  242. logger.info("Sender of %s has been erased, redacting", event.event_id)
  243. return True
  244. return False
  245. def check_event_is_visible(
  246. visibility: str, memberships: StateMap[EventBase]
  247. ) -> bool:
  248. if visibility not in (HistoryVisibility.INVITED, HistoryVisibility.JOINED):
  249. return True
  250. # We now loop through all membership events looking for
  251. # membership states for the requesting server to determine
  252. # if the server is either in the room or has been invited
  253. # into the room.
  254. for ev in memberships.values():
  255. assert get_domain_from_id(ev.state_key) == server_name
  256. memtype = ev.membership
  257. if memtype == Membership.JOIN:
  258. return True
  259. elif memtype == Membership.INVITE:
  260. if visibility == HistoryVisibility.INVITED:
  261. return True
  262. # server has no users in the room: redact
  263. return False
  264. if not check_history_visibility_only:
  265. erased_senders = await storage.main.are_users_erased(e.sender for e in events)
  266. else:
  267. # We don't want to check whether users are erased, which is equivalent
  268. # to no users having been erased.
  269. erased_senders = {}
  270. # Let's check to see if all the events have a history visibility
  271. # of "shared" or "world_readable". If that's the case then we don't
  272. # need to check membership (as we know the server is in the room).
  273. event_to_history_vis = await _event_to_history_vis(storage, events)
  274. # for any with restricted vis, we also need the memberships
  275. event_to_memberships = await _event_to_memberships(
  276. storage,
  277. [
  278. e
  279. for e in events
  280. if event_to_history_vis[e.event_id]
  281. not in (HistoryVisibility.SHARED, HistoryVisibility.WORLD_READABLE)
  282. ],
  283. server_name,
  284. )
  285. to_return = []
  286. for e in events:
  287. erased = is_sender_erased(e, erased_senders)
  288. visible = check_event_is_visible(
  289. event_to_history_vis[e.event_id], event_to_memberships.get(e.event_id, {})
  290. )
  291. if visible and not erased:
  292. to_return.append(e)
  293. elif redact:
  294. to_return.append(prune_event(e))
  295. return to_return
  296. async def _event_to_history_vis(
  297. storage: Storage, events: Collection[EventBase]
  298. ) -> Dict[str, str]:
  299. """Get the history visibility at each of the given events
  300. Returns a map from event id to history_visibility setting
  301. """
  302. # outliers get special treatment here. We don't have the state at that point in the
  303. # room (and attempting to look it up will raise an exception), so all we can really
  304. # do is assume that the requesting server is allowed to see the event. That's
  305. # equivalent to there not being a history_visibility event, so we just exclude
  306. # any outliers from the query.
  307. event_to_state_ids = await storage.state.get_state_ids_for_events(
  308. frozenset(e.event_id for e in events if not e.internal_metadata.is_outlier()),
  309. state_filter=StateFilter.from_types(types=(_HISTORY_VIS_KEY,)),
  310. )
  311. visibility_ids = {
  312. vis_event_id
  313. for vis_event_id in (
  314. state_ids.get(_HISTORY_VIS_KEY) for state_ids in event_to_state_ids.values()
  315. )
  316. if vis_event_id
  317. }
  318. vis_events = await storage.main.get_events(visibility_ids)
  319. result: Dict[str, str] = {}
  320. for event in events:
  321. vis = HistoryVisibility.SHARED
  322. state_ids = event_to_state_ids.get(event.event_id)
  323. # if we didn't find any state for this event, it's an outlier, and we assume
  324. # it's open
  325. visibility_id = None
  326. if state_ids:
  327. visibility_id = state_ids.get(_HISTORY_VIS_KEY)
  328. if visibility_id:
  329. vis_event = vis_events[visibility_id]
  330. vis = vis_event.content.get("history_visibility", HistoryVisibility.SHARED)
  331. assert isinstance(vis, str)
  332. result[event.event_id] = vis
  333. return result
  334. async def _event_to_memberships(
  335. storage: Storage, events: Collection[EventBase], server_name: str
  336. ) -> Dict[str, StateMap[EventBase]]:
  337. """Get the remote membership list at each of the given events
  338. Returns a map from event id to state map, which will contain only membership events
  339. for the given server.
  340. """
  341. if not events:
  342. return {}
  343. # for each event, get the event_ids of the membership state at those events.
  344. #
  345. # TODO: this means that we request the entire membership list. If there are only
  346. # one or two users on this server, and the room is huge, this is very wasteful
  347. # (it means more db work, and churns the *stateGroupMembersCache*).
  348. # It might be that we could extend StateFilter to specify "give me keys matching
  349. # *:<server_name>", to avoid this.
  350. event_to_state_ids = await storage.state.get_state_ids_for_events(
  351. frozenset(e.event_id for e in events),
  352. state_filter=StateFilter.from_types(types=((EventTypes.Member, None),)),
  353. )
  354. # We only want to pull out member events that correspond to the
  355. # server's domain.
  356. #
  357. # event_to_state_ids contains lots of duplicates, so it turns out to be
  358. # cheaper to build a complete event_id => (type, state_key) dict, and then
  359. # filter out the ones we don't want
  360. #
  361. event_id_to_state_key = {
  362. event_id: key
  363. for key_to_eid in event_to_state_ids.values()
  364. for key, event_id in key_to_eid.items()
  365. }
  366. def include(state_key: str) -> bool:
  367. # we avoid using get_domain_from_id here for efficiency.
  368. idx = state_key.find(":")
  369. if idx == -1:
  370. return False
  371. return state_key[idx + 1 :] == server_name
  372. event_map = await storage.main.get_events(
  373. [
  374. e_id
  375. for e_id, (_, state_key) in event_id_to_state_key.items()
  376. if include(state_key)
  377. ]
  378. )
  379. return {
  380. e_id: {
  381. key: event_map[inner_e_id]
  382. for key, inner_e_id in key_to_eid.items()
  383. if inner_e_id in event_map
  384. }
  385. for e_id, key_to_eid in event_to_state_ids.items()
  386. }