visibility.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  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. import operator
  17. from six import iteritems, itervalues
  18. from six.moves import map
  19. from twisted.internet import defer
  20. from synapse.api.constants import EventTypes, Membership
  21. from synapse.events.utils import prune_event
  22. from synapse.storage.state import StateFilter
  23. from synapse.types import get_domain_from_id
  24. logger = logging.getLogger(__name__)
  25. VISIBILITY_PRIORITY = ("world_readable", "shared", "invited", "joined")
  26. MEMBERSHIP_PRIORITY = (
  27. Membership.JOIN,
  28. Membership.INVITE,
  29. Membership.KNOCK,
  30. Membership.LEAVE,
  31. Membership.BAN,
  32. )
  33. @defer.inlineCallbacks
  34. def filter_events_for_client(
  35. store, user_id, events, is_peeking=False, always_include_ids=frozenset()
  36. ):
  37. """
  38. Check which events a user is allowed to see
  39. Args:
  40. store (synapse.storage.DataStore): our datastore (can also be a worker
  41. store)
  42. user_id(str): user id to be checked
  43. events(list[synapse.events.EventBase]): sequence of events to be checked
  44. is_peeking(bool): should be True if:
  45. * the user is not currently a member of the room, and:
  46. * the user has not been a member of the room since the given
  47. events
  48. always_include_ids (set(event_id)): set of event ids to specifically
  49. include (unless sender is ignored)
  50. Returns:
  51. Deferred[list[synapse.events.EventBase]]
  52. """
  53. # Filter out events that have been soft failed so that we don't relay them
  54. # to clients.
  55. events = list(e for e in events if not e.internal_metadata.is_soft_failed())
  56. types = ((EventTypes.RoomHistoryVisibility, ""), (EventTypes.Member, user_id))
  57. event_id_to_state = yield store.get_state_for_events(
  58. frozenset(e.event_id for e in events),
  59. state_filter=StateFilter.from_types(types),
  60. )
  61. ignore_dict_content = yield store.get_global_account_data_by_type_for_user(
  62. "m.ignored_user_list", user_id
  63. )
  64. # FIXME: This will explode if people upload something incorrect.
  65. ignore_list = frozenset(
  66. ignore_dict_content.get("ignored_users", {}).keys()
  67. if ignore_dict_content
  68. else []
  69. )
  70. erased_senders = yield store.are_users_erased((e.sender for e in events))
  71. def allowed(event):
  72. """
  73. Args:
  74. event (synapse.events.EventBase): event to check
  75. Returns:
  76. None|EventBase:
  77. None if the user cannot see this event at all
  78. a redacted copy of the event if they can only see a redacted
  79. version
  80. the original event if they can see it as normal.
  81. """
  82. if not event.is_state() and event.sender in ignore_list:
  83. return None
  84. if event.event_id in always_include_ids:
  85. return event
  86. state = event_id_to_state[event.event_id]
  87. # get the room_visibility at the time of the event.
  88. visibility_event = state.get((EventTypes.RoomHistoryVisibility, ""), None)
  89. if visibility_event:
  90. visibility = visibility_event.content.get("history_visibility", "shared")
  91. else:
  92. visibility = "shared"
  93. if visibility not in VISIBILITY_PRIORITY:
  94. visibility = "shared"
  95. # Always allow history visibility events on boundaries. This is done
  96. # by setting the effective visibility to the least restrictive
  97. # of the old vs new.
  98. if event.type == EventTypes.RoomHistoryVisibility:
  99. prev_content = event.unsigned.get("prev_content", {})
  100. prev_visibility = prev_content.get("history_visibility", None)
  101. if prev_visibility not in VISIBILITY_PRIORITY:
  102. prev_visibility = "shared"
  103. new_priority = VISIBILITY_PRIORITY.index(visibility)
  104. old_priority = VISIBILITY_PRIORITY.index(prev_visibility)
  105. if old_priority < new_priority:
  106. visibility = prev_visibility
  107. # likewise, if the event is the user's own membership event, use
  108. # the 'most joined' membership
  109. membership = None
  110. if event.type == EventTypes.Member and event.state_key == user_id:
  111. membership = event.content.get("membership", None)
  112. if membership not in MEMBERSHIP_PRIORITY:
  113. membership = "leave"
  114. prev_content = event.unsigned.get("prev_content", {})
  115. prev_membership = prev_content.get("membership", None)
  116. if prev_membership not in MEMBERSHIP_PRIORITY:
  117. prev_membership = "leave"
  118. # Always allow the user to see their own leave events, otherwise
  119. # they won't see the room disappear if they reject the invite
  120. if membership == "leave" and (
  121. prev_membership == "join" or prev_membership == "invite"
  122. ):
  123. return event
  124. new_priority = MEMBERSHIP_PRIORITY.index(membership)
  125. old_priority = MEMBERSHIP_PRIORITY.index(prev_membership)
  126. if old_priority < new_priority:
  127. membership = prev_membership
  128. # otherwise, get the user's membership at the time of the event.
  129. if membership is None:
  130. membership_event = state.get((EventTypes.Member, user_id), None)
  131. if membership_event:
  132. membership = membership_event.membership
  133. # if the user was a member of the room at the time of the event,
  134. # they can see it.
  135. if membership == Membership.JOIN:
  136. return event
  137. # otherwise, it depends on the room visibility.
  138. if visibility == "joined":
  139. # we weren't a member at the time of the event, so we can't
  140. # see this event.
  141. return None
  142. elif visibility == "invited":
  143. # user can also see the event if they were *invited* at the time
  144. # of the event.
  145. return event if membership == Membership.INVITE else None
  146. elif visibility == "shared" and is_peeking:
  147. # if the visibility is shared, users cannot see the event unless
  148. # they have *subequently* joined the room (or were members at the
  149. # time, of course)
  150. #
  151. # XXX: if the user has subsequently joined and then left again,
  152. # ideally we would share history up to the point they left. But
  153. # we don't know when they left. We just treat it as though they
  154. # never joined, and restrict access.
  155. return None
  156. # the visibility is either shared or world_readable, and the user was
  157. # not a member at the time. We allow it, provided the original sender
  158. # has not requested their data to be erased, in which case, we return
  159. # a redacted version.
  160. if erased_senders[event.sender]:
  161. return prune_event(event)
  162. return event
  163. # check each event: gives an iterable[None|EventBase]
  164. filtered_events = map(allowed, events)
  165. # remove the None entries
  166. filtered_events = filter(operator.truth, filtered_events)
  167. # we turn it into a list before returning it.
  168. return list(filtered_events)
  169. @defer.inlineCallbacks
  170. def filter_events_for_server(
  171. store, server_name, events, redact=True, check_history_visibility_only=False
  172. ):
  173. """Filter a list of events based on whether given server is allowed to
  174. see them.
  175. Args:
  176. store (DataStore)
  177. server_name (str)
  178. events (iterable[FrozenEvent])
  179. redact (bool): Whether to return a redacted version of the event, or
  180. to filter them out entirely.
  181. check_history_visibility_only (bool): Whether to only check the
  182. history visibility, rather than things like if the sender has been
  183. erased. This is used e.g. during pagination to decide whether to
  184. backfill or not.
  185. Returns
  186. Deferred[list[FrozenEvent]]
  187. """
  188. def is_sender_erased(event, erased_senders):
  189. if erased_senders and erased_senders[event.sender]:
  190. logger.info("Sender of %s has been erased, redacting", event.event_id)
  191. return True
  192. return False
  193. def check_event_is_visible(event, state):
  194. history = state.get((EventTypes.RoomHistoryVisibility, ""), None)
  195. if history:
  196. visibility = history.content.get("history_visibility", "shared")
  197. if visibility in ["invited", "joined"]:
  198. # We now loop through all state events looking for
  199. # membership states for the requesting server to determine
  200. # if the server is either in the room or has been invited
  201. # into the room.
  202. for ev in itervalues(state):
  203. if ev.type != EventTypes.Member:
  204. continue
  205. try:
  206. domain = get_domain_from_id(ev.state_key)
  207. except Exception:
  208. continue
  209. if domain != server_name:
  210. continue
  211. memtype = ev.membership
  212. if memtype == Membership.JOIN:
  213. return True
  214. elif memtype == Membership.INVITE:
  215. if visibility == "invited":
  216. return True
  217. else:
  218. # server has no users in the room: redact
  219. return False
  220. return True
  221. # Lets check to see if all the events have a history visibility
  222. # of "shared" or "world_readable". If thats the case then we don't
  223. # need to check membership (as we know the server is in the room).
  224. event_to_state_ids = yield store.get_state_ids_for_events(
  225. frozenset(e.event_id for e in events),
  226. state_filter=StateFilter.from_types(
  227. types=((EventTypes.RoomHistoryVisibility, ""),)
  228. ),
  229. )
  230. visibility_ids = set()
  231. for sids in itervalues(event_to_state_ids):
  232. hist = sids.get((EventTypes.RoomHistoryVisibility, ""))
  233. if hist:
  234. visibility_ids.add(hist)
  235. # If we failed to find any history visibility events then the default
  236. # is "shared" visiblity.
  237. if not visibility_ids:
  238. all_open = True
  239. else:
  240. event_map = yield store.get_events(visibility_ids)
  241. all_open = all(
  242. e.content.get("history_visibility") in (None, "shared", "world_readable")
  243. for e in itervalues(event_map)
  244. )
  245. if not check_history_visibility_only:
  246. erased_senders = yield store.are_users_erased((e.sender for e in events))
  247. else:
  248. # We don't want to check whether users are erased, which is equivalent
  249. # to no users having been erased.
  250. erased_senders = {}
  251. if all_open:
  252. # all the history_visibility state affecting these events is open, so
  253. # we don't need to filter by membership state. We *do* need to check
  254. # for user erasure, though.
  255. if erased_senders:
  256. to_return = []
  257. for e in events:
  258. if not is_sender_erased(e, erased_senders):
  259. to_return.append(e)
  260. elif redact:
  261. to_return.append(prune_event(e))
  262. return to_return
  263. # If there are no erased users then we can just return the given list
  264. # of events without having to copy it.
  265. return events
  266. # Ok, so we're dealing with events that have non-trivial visibility
  267. # rules, so we need to also get the memberships of the room.
  268. # first, for each event we're wanting to return, get the event_ids
  269. # of the history vis and membership state at those events.
  270. event_to_state_ids = yield store.get_state_ids_for_events(
  271. frozenset(e.event_id for e in events),
  272. state_filter=StateFilter.from_types(
  273. types=((EventTypes.RoomHistoryVisibility, ""), (EventTypes.Member, None))
  274. ),
  275. )
  276. # We only want to pull out member events that correspond to the
  277. # server's domain.
  278. #
  279. # event_to_state_ids contains lots of duplicates, so it turns out to be
  280. # cheaper to build a complete event_id => (type, state_key) dict, and then
  281. # filter out the ones we don't want
  282. #
  283. event_id_to_state_key = {
  284. event_id: key
  285. for key_to_eid in itervalues(event_to_state_ids)
  286. for key, event_id in iteritems(key_to_eid)
  287. }
  288. def include(typ, state_key):
  289. if typ != EventTypes.Member:
  290. return True
  291. # we avoid using get_domain_from_id here for efficiency.
  292. idx = state_key.find(":")
  293. if idx == -1:
  294. return False
  295. return state_key[idx + 1 :] == server_name
  296. event_map = yield store.get_events(
  297. [
  298. e_id
  299. for e_id, key in iteritems(event_id_to_state_key)
  300. if include(key[0], key[1])
  301. ]
  302. )
  303. event_to_state = {
  304. e_id: {
  305. key: event_map[inner_e_id]
  306. for key, inner_e_id in iteritems(key_to_eid)
  307. if inner_e_id in event_map
  308. }
  309. for e_id, key_to_eid in iteritems(event_to_state_ids)
  310. }
  311. to_return = []
  312. for e in events:
  313. erased = is_sender_erased(e, erased_senders)
  314. visible = check_event_is_visible(e, event_to_state[e.event_id])
  315. if visible and not erased:
  316. to_return.append(e)
  317. elif redact:
  318. to_return.append(prune_event(e))
  319. return to_return