visibility.py 16 KB

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