test_visibility.py 12 KB

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