test_visibility.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # Copyright 2018 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import Optional
  16. from unittest.mock import patch
  17. from synapse.api.room_versions import RoomVersions
  18. from synapse.events import EventBase, make_event_from_dict
  19. from synapse.events.snapshot import EventContext
  20. from synapse.types import JsonDict, create_requester
  21. from synapse.visibility import filter_events_for_client, filter_events_for_server
  22. from tests import unittest
  23. from tests.utils import create_room
  24. logger = logging.getLogger(__name__)
  25. TEST_ROOM_ID = "!TEST:ROOM"
  26. class FilterEventsForServerTestCase(unittest.HomeserverTestCase):
  27. def setUp(self) -> None:
  28. super(FilterEventsForServerTestCase, self).setUp()
  29. self.event_creation_handler = self.hs.get_event_creation_handler()
  30. self.event_builder_factory = self.hs.get_event_builder_factory()
  31. self._storage_controllers = self.hs.get_storage_controllers()
  32. assert self._storage_controllers.persistence is not None
  33. self._persistence = self._storage_controllers.persistence
  34. self.get_success(create_room(self.hs, TEST_ROOM_ID, "@someone:ROOM"))
  35. def test_filtering(self) -> None:
  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. self._inject_visibility("@admin:hs", "joined")
  45. for i in range(0, 10):
  46. 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 = self._inject_room_member(user, extra_content={"a": "b"})
  51. events_to_filter.append(evt)
  52. filtered = self.get_success(
  53. filter_events_for_server(
  54. self._storage_controllers, "test_server", "hs", events_to_filter
  55. )
  56. )
  57. # the result should be 5 redacted events, and 5 unredacted events.
  58. for i in range(0, 5):
  59. self.assertEqual(events_to_filter[i].event_id, filtered[i].event_id)
  60. self.assertNotIn("a", filtered[i].content)
  61. for i in range(5, 10):
  62. self.assertEqual(events_to_filter[i].event_id, filtered[i].event_id)
  63. self.assertEqual(filtered[i].content["a"], "b")
  64. def test_filter_outlier(self) -> None:
  65. # outlier events must be returned, for the good of the collective federation
  66. self._inject_room_member("@resident:remote_hs")
  67. self._inject_visibility("@resident:remote_hs", "joined")
  68. outlier = self._inject_outlier()
  69. self.assertEqual(
  70. self.get_success(
  71. filter_events_for_server(
  72. self._storage_controllers, "remote_hs", "hs", [outlier]
  73. )
  74. ),
  75. [outlier],
  76. )
  77. # it should also work when there are other events in the list
  78. evt = self._inject_message("@unerased:local_hs")
  79. filtered = self.get_success(
  80. filter_events_for_server(
  81. self._storage_controllers, "remote_hs", "local_hs", [outlier, evt]
  82. )
  83. )
  84. self.assertEqual(len(filtered), 2, f"expected 2 results, got: {filtered}")
  85. self.assertEqual(filtered[0], outlier)
  86. self.assertEqual(filtered[1].event_id, evt.event_id)
  87. self.assertEqual(filtered[1].content, evt.content)
  88. # ... but other servers should only be able to see the outlier (the other should
  89. # be redacted)
  90. filtered = self.get_success(
  91. filter_events_for_server(
  92. self._storage_controllers, "other_server", "local_hs", [outlier, evt]
  93. )
  94. )
  95. self.assertEqual(filtered[0], outlier)
  96. self.assertEqual(filtered[1].event_id, evt.event_id)
  97. self.assertNotIn("body", filtered[1].content)
  98. def test_erased_user(self) -> None:
  99. # 4 message events, from erased and unerased users, with a membership
  100. # change in the middle of them.
  101. events_to_filter = []
  102. evt = self._inject_message("@unerased:local_hs")
  103. events_to_filter.append(evt)
  104. evt = self._inject_message("@erased:local_hs")
  105. events_to_filter.append(evt)
  106. evt = self._inject_room_member("@joiner:remote_hs")
  107. events_to_filter.append(evt)
  108. evt = self._inject_message("@unerased:local_hs")
  109. events_to_filter.append(evt)
  110. evt = self._inject_message("@erased:local_hs")
  111. events_to_filter.append(evt)
  112. # the erasey user gets erased
  113. self.get_success(
  114. self.hs.get_datastores().main.mark_user_erased("@erased:local_hs")
  115. )
  116. # ... and the filtering happens.
  117. filtered = self.get_success(
  118. filter_events_for_server(
  119. self._storage_controllers, "test_server", "local_hs", events_to_filter
  120. )
  121. )
  122. for i in range(0, len(events_to_filter)):
  123. self.assertEqual(
  124. events_to_filter[i].event_id,
  125. filtered[i].event_id,
  126. "Unexpected event at result position %i" % (i,),
  127. )
  128. for i in (0, 3):
  129. self.assertEqual(
  130. events_to_filter[i].content["body"],
  131. filtered[i].content["body"],
  132. "Unexpected event content at result position %i" % (i,),
  133. )
  134. for i in (1, 4):
  135. self.assertNotIn("body", filtered[i].content)
  136. def _inject_visibility(self, user_id: str, visibility: str) -> EventBase:
  137. content = {"history_visibility": visibility}
  138. builder = self.event_builder_factory.for_room_version(
  139. RoomVersions.V1,
  140. {
  141. "type": "m.room.history_visibility",
  142. "sender": user_id,
  143. "state_key": "",
  144. "room_id": TEST_ROOM_ID,
  145. "content": content,
  146. },
  147. )
  148. event, unpersisted_context = self.get_success(
  149. self.event_creation_handler.create_new_client_event(builder)
  150. )
  151. context = self.get_success(unpersisted_context.persist(event))
  152. self.get_success(self._persistence.persist_event(event, context))
  153. return event
  154. def _inject_room_member(
  155. self,
  156. user_id: str,
  157. membership: str = "join",
  158. extra_content: Optional[JsonDict] = None,
  159. ) -> EventBase:
  160. content = {"membership": membership}
  161. content.update(extra_content or {})
  162. builder = self.event_builder_factory.for_room_version(
  163. RoomVersions.V1,
  164. {
  165. "type": "m.room.member",
  166. "sender": user_id,
  167. "state_key": user_id,
  168. "room_id": TEST_ROOM_ID,
  169. "content": content,
  170. },
  171. )
  172. event, unpersisted_context = self.get_success(
  173. self.event_creation_handler.create_new_client_event(builder)
  174. )
  175. context = self.get_success(unpersisted_context.persist(event))
  176. self.get_success(self._persistence.persist_event(event, context))
  177. return event
  178. def _inject_message(
  179. self, user_id: str, content: Optional[JsonDict] = None
  180. ) -> EventBase:
  181. if content is None:
  182. content = {"body": "testytest", "msgtype": "m.text"}
  183. builder = self.event_builder_factory.for_room_version(
  184. RoomVersions.V1,
  185. {
  186. "type": "m.room.message",
  187. "sender": user_id,
  188. "room_id": TEST_ROOM_ID,
  189. "content": content,
  190. },
  191. )
  192. event, unpersisted_context = self.get_success(
  193. self.event_creation_handler.create_new_client_event(builder)
  194. )
  195. context = self.get_success(unpersisted_context.persist(event))
  196. self.get_success(self._persistence.persist_event(event, context))
  197. return event
  198. def _inject_outlier(self) -> EventBase:
  199. builder = self.event_builder_factory.for_room_version(
  200. RoomVersions.V1,
  201. {
  202. "type": "m.room.member",
  203. "sender": "@test:user",
  204. "state_key": "@test:user",
  205. "room_id": TEST_ROOM_ID,
  206. "content": {"membership": "join"},
  207. },
  208. )
  209. event = self.get_success(builder.build(prev_event_ids=[], auth_event_ids=[]))
  210. event.internal_metadata.outlier = True
  211. self.get_success(
  212. self._persistence.persist_event(
  213. event, EventContext.for_outlier(self._storage_controllers)
  214. )
  215. )
  216. return event
  217. class FilterEventsForClientTestCase(unittest.FederatingHomeserverTestCase):
  218. def test_out_of_band_invite_rejection(self) -> None:
  219. # this is where we have received an invite event over federation, and then
  220. # rejected it.
  221. invite_pdu = {
  222. "room_id": "!room:id",
  223. "depth": 1,
  224. "auth_events": [],
  225. "prev_events": [],
  226. "origin_server_ts": 1,
  227. "sender": "@someone:" + self.OTHER_SERVER_NAME,
  228. "type": "m.room.member",
  229. "state_key": "@user:test",
  230. "content": {"membership": "invite"},
  231. }
  232. self.add_hashes_and_signatures_from_other_server(invite_pdu)
  233. invite_event_id = make_event_from_dict(invite_pdu, RoomVersions.V9).event_id
  234. self.get_success(
  235. self.hs.get_federation_server().on_invite_request(
  236. self.OTHER_SERVER_NAME,
  237. invite_pdu,
  238. "9",
  239. )
  240. )
  241. # stub out do_remotely_reject_invite so that we fall back to a locally-
  242. # generated rejection
  243. with patch.object(
  244. self.hs.get_federation_handler(),
  245. "do_remotely_reject_invite",
  246. side_effect=Exception(),
  247. ):
  248. reject_event_id, _ = self.get_success(
  249. self.hs.get_room_member_handler().remote_reject_invite(
  250. invite_event_id,
  251. txn_id=None,
  252. requester=create_requester("@user:test"),
  253. content={},
  254. )
  255. )
  256. invite_event, reject_event = self.get_success(
  257. self.hs.get_datastores().main.get_events_as_list(
  258. [invite_event_id, reject_event_id]
  259. )
  260. )
  261. # the invited user should be able to see both the invite and the rejection
  262. self.assertEqual(
  263. self.get_success(
  264. filter_events_for_client(
  265. self.hs.get_storage_controllers(),
  266. "@user:test",
  267. [invite_event, reject_event],
  268. )
  269. ),
  270. [invite_event, reject_event],
  271. )
  272. # other users should see neither
  273. self.assertEqual(
  274. self.get_success(
  275. filter_events_for_client(
  276. self.hs.get_storage_controllers(),
  277. "@other:test",
  278. [invite_event, reject_event],
  279. )
  280. ),
  281. [],
  282. )