visibility.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. from twisted.internet import defer
  16. from synapse.api.constants import Membership, EventTypes
  17. from synapse.util.logcontext import preserve_fn, preserve_context_over_deferred
  18. import logging
  19. logger = logging.getLogger(__name__)
  20. VISIBILITY_PRIORITY = (
  21. "world_readable",
  22. "shared",
  23. "invited",
  24. "joined",
  25. )
  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_clients(store, user_tuples, events, event_id_to_state,
  35. always_include_ids=frozenset()):
  36. """ Returns dict of user_id -> list of events that user is allowed to
  37. see.
  38. Args:
  39. user_tuples (str, bool): (user id, is_peeking) for each user to be
  40. checked. is_peeking should be true if:
  41. * the user is not currently a member of the room, and:
  42. * the user has not been a member of the room since the
  43. given events
  44. events ([synapse.events.EventBase]): list of events to filter
  45. always_include_ids (set(event_id)): set of event ids to specifically
  46. include (unless sender is ignored)
  47. """
  48. forgotten = yield preserve_context_over_deferred(defer.gatherResults([
  49. defer.maybeDeferred(
  50. preserve_fn(store.who_forgot_in_room),
  51. room_id,
  52. )
  53. for room_id in frozenset(e.room_id for e in events)
  54. ], consumeErrors=True))
  55. # Set of membership event_ids that have been forgotten
  56. event_id_forgotten = frozenset(
  57. row["event_id"] for rows in forgotten for row in rows
  58. )
  59. ignore_dict_content = yield store.get_global_account_data_by_type_for_users(
  60. "m.ignored_user_list", user_ids=[user_id for user_id, _ in user_tuples]
  61. )
  62. # FIXME: This will explode if people upload something incorrect.
  63. ignore_dict = {
  64. user_id: frozenset(
  65. content.get("ignored_users", {}).keys() if content else []
  66. )
  67. for user_id, content in ignore_dict_content.items()
  68. }
  69. def allowed(event, user_id, is_peeking, ignore_list):
  70. """
  71. Args:
  72. event (synapse.events.EventBase): event to check
  73. user_id (str)
  74. is_peeking (bool)
  75. ignore_list (list): list of users to ignore
  76. """
  77. if not event.is_state() and event.sender in ignore_list:
  78. return False
  79. if event.event_id in always_include_ids:
  80. return True
  81. state = event_id_to_state[event.event_id]
  82. # get the room_visibility at the time of the event.
  83. visibility_event = state.get((EventTypes.RoomHistoryVisibility, ""), None)
  84. if visibility_event:
  85. visibility = visibility_event.content.get("history_visibility", "shared")
  86. else:
  87. visibility = "shared"
  88. if visibility not in VISIBILITY_PRIORITY:
  89. visibility = "shared"
  90. # if it was world_readable, it's easy: everyone can read it
  91. if visibility == "world_readable":
  92. return True
  93. # Always allow history visibility events on boundaries. This is done
  94. # by setting the effective visibility to the least restrictive
  95. # of the old vs new.
  96. if event.type == EventTypes.RoomHistoryVisibility:
  97. prev_content = event.unsigned.get("prev_content", {})
  98. prev_visibility = prev_content.get("history_visibility", None)
  99. if prev_visibility not in VISIBILITY_PRIORITY:
  100. prev_visibility = "shared"
  101. new_priority = VISIBILITY_PRIORITY.index(visibility)
  102. old_priority = VISIBILITY_PRIORITY.index(prev_visibility)
  103. if old_priority < new_priority:
  104. visibility = prev_visibility
  105. # likewise, if the event is the user's own membership event, use
  106. # the 'most joined' membership
  107. membership = None
  108. if event.type == EventTypes.Member and event.state_key == user_id:
  109. membership = event.content.get("membership", None)
  110. if membership not in MEMBERSHIP_PRIORITY:
  111. membership = "leave"
  112. prev_content = event.unsigned.get("prev_content", {})
  113. prev_membership = prev_content.get("membership", None)
  114. if prev_membership not in MEMBERSHIP_PRIORITY:
  115. prev_membership = "leave"
  116. # Always allow the user to see their own leave events, otherwise
  117. # they won't see the room disappear if they reject the invite
  118. if membership == "leave" and (
  119. prev_membership == "join" or prev_membership == "invite"
  120. ):
  121. return True
  122. new_priority = MEMBERSHIP_PRIORITY.index(membership)
  123. old_priority = MEMBERSHIP_PRIORITY.index(prev_membership)
  124. if old_priority < new_priority:
  125. membership = prev_membership
  126. # otherwise, get the user's membership at the time of the event.
  127. if membership is None:
  128. membership_event = state.get((EventTypes.Member, user_id), None)
  129. if membership_event:
  130. if membership_event.event_id not in event_id_forgotten:
  131. membership = membership_event.membership
  132. # if the user was a member of the room at the time of the event,
  133. # they can see it.
  134. if membership == Membership.JOIN:
  135. return True
  136. if visibility == "joined":
  137. # we weren't a member at the time of the event, so we can't
  138. # see this event.
  139. return False
  140. elif visibility == "invited":
  141. # user can also see the event if they were *invited* at the time
  142. # of the event.
  143. return membership == Membership.INVITE
  144. else:
  145. # visibility is shared: user can also see the event if they have
  146. # become a member since the event
  147. #
  148. # XXX: if the user has subsequently joined and then left again,
  149. # ideally we would share history up to the point they left. But
  150. # we don't know when they left.
  151. return not is_peeking
  152. defer.returnValue({
  153. user_id: [
  154. event
  155. for event in events
  156. if allowed(event, user_id, is_peeking, ignore_dict.get(user_id, []))
  157. ]
  158. for user_id, is_peeking in user_tuples
  159. })
  160. @defer.inlineCallbacks
  161. def filter_events_for_client(store, user_id, events, is_peeking=False,
  162. always_include_ids=frozenset()):
  163. """
  164. Check which events a user is allowed to see
  165. Args:
  166. user_id(str): user id to be checked
  167. events([synapse.events.EventBase]): list of events to be checked
  168. is_peeking(bool): should be True if:
  169. * the user is not currently a member of the room, and:
  170. * the user has not been a member of the room since the given
  171. events
  172. Returns:
  173. [synapse.events.EventBase]
  174. """
  175. types = (
  176. (EventTypes.RoomHistoryVisibility, ""),
  177. (EventTypes.Member, user_id),
  178. )
  179. event_id_to_state = yield store.get_state_for_events(
  180. frozenset(e.event_id for e in events),
  181. types=types
  182. )
  183. res = yield filter_events_for_clients(
  184. store, [(user_id, is_peeking)], events, event_id_to_state,
  185. always_include_ids=always_include_ids,
  186. )
  187. defer.returnValue(res.get(user_id, []))