1
0

test_visibility.py 11 KB

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