test_visibility.py 12 KB

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