visibility.py 15 KB

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