test_visibility.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. self.get_success(create_room(self.hs, TEST_ROOM_ID, "@someone:ROOM"))
  33. def test_filtering(self) -> None:
  34. #
  35. # The events to be filtered consist of 10 membership events (it doesn't
  36. # really matter if they are joins or leaves, so let's make them joins).
  37. # One of those membership events is going to be for a user on the
  38. # server we are filtering for (so we can check the filtering is doing
  39. # the right thing).
  40. #
  41. # before we do that, we persist some other events to act as state.
  42. self._inject_visibility("@admin:hs", "joined")
  43. for i in range(0, 10):
  44. self._inject_room_member("@resident%i:hs" % i)
  45. events_to_filter = []
  46. for i in range(0, 10):
  47. user = "@user%i:%s" % (i, "test_server" if i == 5 else "other_server")
  48. evt = self._inject_room_member(user, extra_content={"a": "b"})
  49. events_to_filter.append(evt)
  50. filtered = self.get_success(
  51. filter_events_for_server(
  52. self._storage_controllers, "test_server", "hs", events_to_filter
  53. )
  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. def test_filter_outlier(self) -> None:
  63. # outlier events must be returned, for the good of the collective federation
  64. self._inject_room_member("@resident:remote_hs")
  65. self._inject_visibility("@resident:remote_hs", "joined")
  66. outlier = self._inject_outlier()
  67. self.assertEqual(
  68. self.get_success(
  69. filter_events_for_server(
  70. self._storage_controllers, "remote_hs", "hs", [outlier]
  71. )
  72. ),
  73. [outlier],
  74. )
  75. # it should also work when there are other events in the list
  76. evt = self._inject_message("@unerased:local_hs")
  77. filtered = self.get_success(
  78. filter_events_for_server(
  79. self._storage_controllers, "remote_hs", "local_hs", [outlier, evt]
  80. )
  81. )
  82. self.assertEqual(len(filtered), 2, f"expected 2 results, got: {filtered}")
  83. self.assertEqual(filtered[0], outlier)
  84. self.assertEqual(filtered[1].event_id, evt.event_id)
  85. self.assertEqual(filtered[1].content, evt.content)
  86. # ... but other servers should only be able to see the outlier (the other should
  87. # be redacted)
  88. filtered = self.get_success(
  89. filter_events_for_server(
  90. self._storage_controllers, "other_server", "local_hs", [outlier, evt]
  91. )
  92. )
  93. self.assertEqual(filtered[0], outlier)
  94. self.assertEqual(filtered[1].event_id, evt.event_id)
  95. self.assertNotIn("body", filtered[1].content)
  96. def test_erased_user(self) -> None:
  97. # 4 message events, from erased and unerased users, with a membership
  98. # change in the middle of them.
  99. events_to_filter = []
  100. evt = self._inject_message("@unerased:local_hs")
  101. events_to_filter.append(evt)
  102. evt = self._inject_message("@erased:local_hs")
  103. events_to_filter.append(evt)
  104. evt = self._inject_room_member("@joiner:remote_hs")
  105. events_to_filter.append(evt)
  106. evt = self._inject_message("@unerased:local_hs")
  107. events_to_filter.append(evt)
  108. evt = self._inject_message("@erased:local_hs")
  109. events_to_filter.append(evt)
  110. # the erasey user gets erased
  111. self.get_success(
  112. self.hs.get_datastores().main.mark_user_erased("@erased:local_hs")
  113. )
  114. # ... and the filtering happens.
  115. filtered = self.get_success(
  116. filter_events_for_server(
  117. self._storage_controllers, "test_server", "local_hs", events_to_filter
  118. )
  119. )
  120. for i in range(0, len(events_to_filter)):
  121. self.assertEqual(
  122. events_to_filter[i].event_id,
  123. filtered[i].event_id,
  124. "Unexpected event at result position %i" % (i,),
  125. )
  126. for i in (0, 3):
  127. self.assertEqual(
  128. events_to_filter[i].content["body"],
  129. filtered[i].content["body"],
  130. "Unexpected event content at result position %i" % (i,),
  131. )
  132. for i in (1, 4):
  133. self.assertNotIn("body", filtered[i].content)
  134. def _inject_visibility(self, user_id: str, visibility: str) -> EventBase:
  135. content = {"history_visibility": visibility}
  136. builder = self.event_builder_factory.for_room_version(
  137. RoomVersions.V1,
  138. {
  139. "type": "m.room.history_visibility",
  140. "sender": user_id,
  141. "state_key": "",
  142. "room_id": TEST_ROOM_ID,
  143. "content": content,
  144. },
  145. )
  146. event, context = self.get_success(
  147. self.event_creation_handler.create_new_client_event(builder)
  148. )
  149. self.get_success(
  150. self._storage_controllers.persistence.persist_event(event, context)
  151. )
  152. return event
  153. def _inject_room_member(
  154. self,
  155. user_id: str,
  156. membership: str = "join",
  157. extra_content: Optional[JsonDict] = None,
  158. ) -> EventBase:
  159. content = {"membership": membership}
  160. content.update(extra_content or {})
  161. builder = self.event_builder_factory.for_room_version(
  162. RoomVersions.V1,
  163. {
  164. "type": "m.room.member",
  165. "sender": user_id,
  166. "state_key": user_id,
  167. "room_id": TEST_ROOM_ID,
  168. "content": content,
  169. },
  170. )
  171. event, context = self.get_success(
  172. self.event_creation_handler.create_new_client_event(builder)
  173. )
  174. self.get_success(
  175. self._storage_controllers.persistence.persist_event(event, context)
  176. )
  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, context = self.get_success(
  193. self.event_creation_handler.create_new_client_event(builder)
  194. )
  195. self.get_success(
  196. self._storage_controllers.persistence.persist_event(event, context)
  197. )
  198. return event
  199. def _inject_outlier(self) -> EventBase:
  200. builder = self.event_builder_factory.for_room_version(
  201. RoomVersions.V1,
  202. {
  203. "type": "m.room.member",
  204. "sender": "@test:user",
  205. "state_key": "@test:user",
  206. "room_id": TEST_ROOM_ID,
  207. "content": {"membership": "join"},
  208. },
  209. )
  210. event = self.get_success(builder.build(prev_event_ids=[], auth_event_ids=[]))
  211. event.internal_metadata.outlier = True
  212. self.get_success(
  213. self._storage_controllers.persistence.persist_event(
  214. event, EventContext.for_outlier(self._storage_controllers)
  215. )
  216. )
  217. return event
  218. class FilterEventsForClientTestCase(unittest.FederatingHomeserverTestCase):
  219. def test_out_of_band_invite_rejection(self):
  220. # this is where we have received an invite event over federation, and then
  221. # rejected it.
  222. invite_pdu = {
  223. "room_id": "!room:id",
  224. "depth": 1,
  225. "auth_events": [],
  226. "prev_events": [],
  227. "origin_server_ts": 1,
  228. "sender": "@someone:" + self.OTHER_SERVER_NAME,
  229. "type": "m.room.member",
  230. "state_key": "@user:test",
  231. "content": {"membership": "invite"},
  232. }
  233. self.add_hashes_and_signatures_from_other_server(invite_pdu)
  234. invite_event_id = make_event_from_dict(invite_pdu, RoomVersions.V9).event_id
  235. self.get_success(
  236. self.hs.get_federation_server().on_invite_request(
  237. self.OTHER_SERVER_NAME,
  238. invite_pdu,
  239. "9",
  240. )
  241. )
  242. # stub out do_remotely_reject_invite so that we fall back to a locally-
  243. # generated rejection
  244. with patch.object(
  245. self.hs.get_federation_handler(),
  246. "do_remotely_reject_invite",
  247. side_effect=Exception(),
  248. ):
  249. reject_event_id, _ = self.get_success(
  250. self.hs.get_room_member_handler().remote_reject_invite(
  251. invite_event_id,
  252. txn_id=None,
  253. requester=create_requester("@user:test"),
  254. content={},
  255. )
  256. )
  257. invite_event, reject_event = self.get_success(
  258. self.hs.get_datastores().main.get_events_as_list(
  259. [invite_event_id, reject_event_id]
  260. )
  261. )
  262. # the invited user should be able to see both the invite and the rejection
  263. self.assertEqual(
  264. self.get_success(
  265. filter_events_for_client(
  266. self.hs.get_storage_controllers(),
  267. "@user:test",
  268. [invite_event, reject_event],
  269. )
  270. ),
  271. [invite_event, reject_event],
  272. )
  273. # other users should see neither
  274. self.assertEqual(
  275. self.get_success(
  276. filter_events_for_client(
  277. self.hs.get_storage_controllers(),
  278. "@other:test",
  279. [invite_event, reject_event],
  280. )
  281. ),
  282. [],
  283. )