visibility.py 17 KB

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