test_visibility.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector 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. from twisted.internet import defer
  17. from twisted.internet.defer import succeed
  18. from synapse.api.room_versions import RoomVersions
  19. from synapse.events import FrozenEvent
  20. from synapse.visibility import filter_events_for_server
  21. import tests.unittest
  22. from tests.utils import create_room, setup_test_homeserver
  23. logger = logging.getLogger(__name__)
  24. TEST_ROOM_ID = "!TEST:ROOM"
  25. class FilterEventsForServerTestCase(tests.unittest.TestCase):
  26. @defer.inlineCallbacks
  27. def setUp(self):
  28. self.hs = yield setup_test_homeserver(self.addCleanup)
  29. self.event_creation_handler = self.hs.get_event_creation_handler()
  30. self.event_builder_factory = self.hs.get_event_builder_factory()
  31. self.store = self.hs.get_datastore()
  32. yield create_room(self.hs, TEST_ROOM_ID, "@someone:ROOM")
  33. @defer.inlineCallbacks
  34. def test_filtering(self):
  35. #
  36. # The events to be filtered consist of 10 membership events (it doesn't
  37. # really matter if they are joins or leaves, so let's make them joins).
  38. # One of those membership events is going to be for a user on the
  39. # server we are filtering for (so we can check the filtering is doing
  40. # the right thing).
  41. #
  42. # before we do that, we persist some other events to act as state.
  43. self.inject_visibility("@admin:hs", "joined")
  44. for i in range(0, 10):
  45. yield self.inject_room_member("@resident%i:hs" % i)
  46. events_to_filter = []
  47. for i in range(0, 10):
  48. user = "@user%i:%s" % (i, "test_server" if i == 5 else "other_server")
  49. evt = yield self.inject_room_member(user, extra_content={"a": "b"})
  50. events_to_filter.append(evt)
  51. filtered = yield filter_events_for_server(
  52. self.store, "test_server", events_to_filter
  53. )
  54. # the result should be 5 redacted events, and 5 unredacted events.
  55. for i in range(0, 5):
  56. self.assertEqual(events_to_filter[i].event_id, filtered[i].event_id)
  57. self.assertNotIn("a", filtered[i].content)
  58. for i in range(5, 10):
  59. self.assertEqual(events_to_filter[i].event_id, filtered[i].event_id)
  60. self.assertEqual(filtered[i].content["a"], "b")
  61. @defer.inlineCallbacks
  62. def test_erased_user(self):
  63. # 4 message events, from erased and unerased users, with a membership
  64. # change in the middle of them.
  65. events_to_filter = []
  66. evt = yield self.inject_message("@unerased:local_hs")
  67. events_to_filter.append(evt)
  68. evt = yield self.inject_message("@erased:local_hs")
  69. events_to_filter.append(evt)
  70. evt = yield self.inject_room_member("@joiner:remote_hs")
  71. events_to_filter.append(evt)
  72. evt = yield self.inject_message("@unerased:local_hs")
  73. events_to_filter.append(evt)
  74. evt = yield self.inject_message("@erased:local_hs")
  75. events_to_filter.append(evt)
  76. # the erasey user gets erased
  77. yield self.hs.get_datastore().mark_user_erased("@erased:local_hs")
  78. # ... and the filtering happens.
  79. filtered = yield filter_events_for_server(
  80. self.store, "test_server", events_to_filter
  81. )
  82. for i in range(0, len(events_to_filter)):
  83. self.assertEqual(
  84. events_to_filter[i].event_id,
  85. filtered[i].event_id,
  86. "Unexpected event at result position %i" % (i,),
  87. )
  88. for i in (0, 3):
  89. self.assertEqual(
  90. events_to_filter[i].content["body"],
  91. filtered[i].content["body"],
  92. "Unexpected event content at result position %i" % (i,),
  93. )
  94. for i in (1, 4):
  95. self.assertNotIn("body", filtered[i].content)
  96. @defer.inlineCallbacks
  97. def inject_visibility(self, user_id, visibility):
  98. content = {"history_visibility": visibility}
  99. builder = self.event_builder_factory.for_room_version(
  100. RoomVersions.V1,
  101. {
  102. "type": "m.room.history_visibility",
  103. "sender": user_id,
  104. "state_key": "",
  105. "room_id": TEST_ROOM_ID,
  106. "content": content,
  107. },
  108. )
  109. event, context = yield self.event_creation_handler.create_new_client_event(
  110. builder
  111. )
  112. yield self.hs.get_datastore().persist_event(event, context)
  113. return event
  114. @defer.inlineCallbacks
  115. def inject_room_member(self, user_id, membership="join", extra_content={}):
  116. content = {"membership": membership}
  117. content.update(extra_content)
  118. builder = self.event_builder_factory.for_room_version(
  119. RoomVersions.V1,
  120. {
  121. "type": "m.room.member",
  122. "sender": user_id,
  123. "state_key": user_id,
  124. "room_id": TEST_ROOM_ID,
  125. "content": content,
  126. },
  127. )
  128. event, context = yield self.event_creation_handler.create_new_client_event(
  129. builder
  130. )
  131. yield self.hs.get_datastore().persist_event(event, context)
  132. return event
  133. @defer.inlineCallbacks
  134. def inject_message(self, user_id, content=None):
  135. if content is None:
  136. content = {"body": "testytest", "msgtype": "m.text"}
  137. builder = self.event_builder_factory.for_room_version(
  138. RoomVersions.V1,
  139. {
  140. "type": "m.room.message",
  141. "sender": user_id,
  142. "room_id": TEST_ROOM_ID,
  143. "content": content,
  144. },
  145. )
  146. event, context = yield self.event_creation_handler.create_new_client_event(
  147. builder
  148. )
  149. yield self.hs.get_datastore().persist_event(event, context)
  150. return event
  151. @defer.inlineCallbacks
  152. def test_large_room(self):
  153. # see what happens when we have a large room with hundreds of thousands
  154. # of membership events
  155. # As above, the events to be filtered consist of 10 membership events,
  156. # where one of them is for a user on the server we are filtering for.
  157. import cProfile
  158. import pstats
  159. import time
  160. # we stub out the store, because building up all that state the normal
  161. # way is very slow.
  162. test_store = _TestStore()
  163. # our initial state is 100000 membership events and one
  164. # history_visibility event.
  165. room_state = []
  166. history_visibility_evt = FrozenEvent(
  167. {
  168. "event_id": "$history_vis",
  169. "type": "m.room.history_visibility",
  170. "sender": "@resident_user_0:test.com",
  171. "state_key": "",
  172. "room_id": TEST_ROOM_ID,
  173. "content": {"history_visibility": "joined"},
  174. }
  175. )
  176. room_state.append(history_visibility_evt)
  177. test_store.add_event(history_visibility_evt)
  178. for i in range(0, 100000):
  179. user = "@resident_user_%i:test.com" % (i,)
  180. evt = FrozenEvent(
  181. {
  182. "event_id": "$res_event_%i" % (i,),
  183. "type": "m.room.member",
  184. "state_key": user,
  185. "sender": user,
  186. "room_id": TEST_ROOM_ID,
  187. "content": {"membership": "join", "extra": "zzz,"},
  188. }
  189. )
  190. room_state.append(evt)
  191. test_store.add_event(evt)
  192. events_to_filter = []
  193. for i in range(0, 10):
  194. user = "@user%i:%s" % (i, "test_server" if i == 5 else "other_server")
  195. evt = FrozenEvent(
  196. {
  197. "event_id": "$evt%i" % (i,),
  198. "type": "m.room.member",
  199. "state_key": user,
  200. "sender": user,
  201. "room_id": TEST_ROOM_ID,
  202. "content": {"membership": "join", "extra": "zzz"},
  203. }
  204. )
  205. events_to_filter.append(evt)
  206. room_state.append(evt)
  207. test_store.add_event(evt)
  208. test_store.set_state_ids_for_event(
  209. evt, {(e.type, e.state_key): e.event_id for e in room_state}
  210. )
  211. pr = cProfile.Profile()
  212. pr.enable()
  213. logger.info("Starting filtering")
  214. start = time.time()
  215. filtered = yield filter_events_for_server(
  216. test_store, "test_server", events_to_filter
  217. )
  218. logger.info("Filtering took %f seconds", time.time() - start)
  219. pr.disable()
  220. with open("filter_events_for_server.profile", "w+") as f:
  221. ps = pstats.Stats(pr, stream=f).sort_stats("cumulative")
  222. ps.print_stats()
  223. # the result should be 5 redacted events, and 5 unredacted events.
  224. for i in range(0, 5):
  225. self.assertEqual(events_to_filter[i].event_id, filtered[i].event_id)
  226. self.assertNotIn("extra", filtered[i].content)
  227. for i in range(5, 10):
  228. self.assertEqual(events_to_filter[i].event_id, filtered[i].event_id)
  229. self.assertEqual(filtered[i].content["extra"], "zzz")
  230. test_large_room.skip = "Disabled by default because it's slow"
  231. class _TestStore(object):
  232. """Implements a few methods of the DataStore, so that we can test
  233. filter_events_for_server
  234. """
  235. def __init__(self):
  236. # data for get_events: a map from event_id to event
  237. self.events = {}
  238. # data for get_state_ids_for_events mock: a map from event_id to
  239. # a map from (type_state_key) -> event_id for the state at that
  240. # event
  241. self.state_ids_for_events = {}
  242. def add_event(self, event):
  243. self.events[event.event_id] = event
  244. def set_state_ids_for_event(self, event, state):
  245. self.state_ids_for_events[event.event_id] = state
  246. def get_state_ids_for_events(self, events, types):
  247. res = {}
  248. include_memberships = False
  249. for (type, state_key) in types:
  250. if type == "m.room.history_visibility":
  251. continue
  252. if type != "m.room.member" or state_key is not None:
  253. raise RuntimeError(
  254. "Unimplemented: get_state_ids with type (%s, %s)"
  255. % (type, state_key)
  256. )
  257. include_memberships = True
  258. if include_memberships:
  259. for event_id in events:
  260. res[event_id] = self.state_ids_for_events[event_id]
  261. else:
  262. k = ("m.room.history_visibility", "")
  263. for event_id in events:
  264. hve = self.state_ids_for_events[event_id][k]
  265. res[event_id] = {k: hve}
  266. return succeed(res)
  267. def get_events(self, events):
  268. return succeed({event_id: self.events[event_id] for event_id in events})
  269. def are_users_erased(self, users):
  270. return succeed({u: False for u in users})