visibility.py 16 KB

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