test_visibility.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 = self.hs.get_storage()
  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(self.storage, "test_server", events_to_filter)
  52. )
  53. # the result should be 5 redacted events, and 5 unredacted events.
  54. for i in range(0, 5):
  55. self.assertEqual(events_to_filter[i].event_id, filtered[i].event_id)
  56. self.assertNotIn("a", filtered[i].content)
  57. for i in range(5, 10):
  58. self.assertEqual(events_to_filter[i].event_id, filtered[i].event_id)
  59. self.assertEqual(filtered[i].content["a"], "b")
  60. def test_filter_outlier(self) -> None:
  61. # outlier events must be returned, for the good of the collective federation
  62. self._inject_room_member("@resident:remote_hs")
  63. self._inject_visibility("@resident:remote_hs", "joined")
  64. outlier = self._inject_outlier()
  65. self.assertEqual(
  66. self.get_success(
  67. filter_events_for_server(self.storage, "remote_hs", [outlier])
  68. ),
  69. [outlier],
  70. )
  71. # it should also work when there are other events in the list
  72. evt = self._inject_message("@unerased:local_hs")
  73. filtered = self.get_success(
  74. filter_events_for_server(self.storage, "remote_hs", [outlier, evt])
  75. )
  76. self.assertEqual(len(filtered), 2, f"expected 2 results, got: {filtered}")
  77. self.assertEqual(filtered[0], outlier)
  78. self.assertEqual(filtered[1].event_id, evt.event_id)
  79. self.assertEqual(filtered[1].content, evt.content)
  80. # ... but other servers should only be able to see the outlier (the other should
  81. # be redacted)
  82. filtered = self.get_success(
  83. filter_events_for_server(self.storage, "other_server", [outlier, evt])
  84. )
  85. self.assertEqual(filtered[0], outlier)
  86. self.assertEqual(filtered[1].event_id, evt.event_id)
  87. self.assertNotIn("body", filtered[1].content)
  88. def test_erased_user(self) -> None:
  89. # 4 message events, from erased and unerased users, with a membership
  90. # change in the middle of them.
  91. events_to_filter = []
  92. evt = self._inject_message("@unerased:local_hs")
  93. events_to_filter.append(evt)
  94. evt = self._inject_message("@erased:local_hs")
  95. events_to_filter.append(evt)
  96. evt = self._inject_room_member("@joiner:remote_hs")
  97. events_to_filter.append(evt)
  98. evt = self._inject_message("@unerased:local_hs")
  99. events_to_filter.append(evt)
  100. evt = self._inject_message("@erased:local_hs")
  101. events_to_filter.append(evt)
  102. # the erasey user gets erased
  103. self.get_success(
  104. self.hs.get_datastores().main.mark_user_erased("@erased:local_hs")
  105. )
  106. # ... and the filtering happens.
  107. filtered = self.get_success(
  108. filter_events_for_server(self.storage, "test_server", events_to_filter)
  109. )
  110. for i in range(0, len(events_to_filter)):
  111. self.assertEqual(
  112. events_to_filter[i].event_id,
  113. filtered[i].event_id,
  114. "Unexpected event at result position %i" % (i,),
  115. )
  116. for i in (0, 3):
  117. self.assertEqual(
  118. events_to_filter[i].content["body"],
  119. filtered[i].content["body"],
  120. "Unexpected event content at result position %i" % (i,),
  121. )
  122. for i in (1, 4):
  123. self.assertNotIn("body", filtered[i].content)
  124. def _inject_visibility(self, user_id: str, visibility: str) -> EventBase:
  125. content = {"history_visibility": visibility}
  126. builder = self.event_builder_factory.for_room_version(
  127. RoomVersions.V1,
  128. {
  129. "type": "m.room.history_visibility",
  130. "sender": user_id,
  131. "state_key": "",
  132. "room_id": TEST_ROOM_ID,
  133. "content": content,
  134. },
  135. )
  136. event, context = self.get_success(
  137. self.event_creation_handler.create_new_client_event(builder)
  138. )
  139. self.get_success(self.storage.persistence.persist_event(event, context))
  140. return event
  141. def _inject_room_member(
  142. self,
  143. user_id: str,
  144. membership: str = "join",
  145. extra_content: Optional[JsonDict] = None,
  146. ) -> EventBase:
  147. content = {"membership": membership}
  148. content.update(extra_content or {})
  149. builder = self.event_builder_factory.for_room_version(
  150. RoomVersions.V1,
  151. {
  152. "type": "m.room.member",
  153. "sender": user_id,
  154. "state_key": user_id,
  155. "room_id": TEST_ROOM_ID,
  156. "content": content,
  157. },
  158. )
  159. event, context = self.get_success(
  160. self.event_creation_handler.create_new_client_event(builder)
  161. )
  162. self.get_success(self.storage.persistence.persist_event(event, context))
  163. return event
  164. def _inject_message(
  165. self, user_id: str, content: Optional[JsonDict] = None
  166. ) -> EventBase:
  167. if content is None:
  168. content = {"body": "testytest", "msgtype": "m.text"}
  169. builder = self.event_builder_factory.for_room_version(
  170. RoomVersions.V1,
  171. {
  172. "type": "m.room.message",
  173. "sender": user_id,
  174. "room_id": TEST_ROOM_ID,
  175. "content": content,
  176. },
  177. )
  178. event, context = self.get_success(
  179. self.event_creation_handler.create_new_client_event(builder)
  180. )
  181. self.get_success(self.storage.persistence.persist_event(event, context))
  182. return event
  183. def _inject_outlier(self) -> EventBase:
  184. builder = self.event_builder_factory.for_room_version(
  185. RoomVersions.V1,
  186. {
  187. "type": "m.room.member",
  188. "sender": "@test:user",
  189. "state_key": "@test:user",
  190. "room_id": TEST_ROOM_ID,
  191. "content": {"membership": "join"},
  192. },
  193. )
  194. event = self.get_success(builder.build(prev_event_ids=[], auth_event_ids=[]))
  195. event.internal_metadata.outlier = True
  196. self.get_success(
  197. self.storage.persistence.persist_event(
  198. event, EventContext.for_outlier(self.storage)
  199. )
  200. )
  201. return event
  202. class FilterEventsForClientTestCase(unittest.FederatingHomeserverTestCase):
  203. def test_out_of_band_invite_rejection(self):
  204. # this is where we have received an invite event over federation, and then
  205. # rejected it.
  206. invite_pdu = {
  207. "room_id": "!room:id",
  208. "depth": 1,
  209. "auth_events": [],
  210. "prev_events": [],
  211. "origin_server_ts": 1,
  212. "sender": "@someone:" + self.OTHER_SERVER_NAME,
  213. "type": "m.room.member",
  214. "state_key": "@user:test",
  215. "content": {"membership": "invite"},
  216. }
  217. self.add_hashes_and_signatures(invite_pdu)
  218. invite_event_id = make_event_from_dict(invite_pdu, RoomVersions.V9).event_id
  219. self.get_success(
  220. self.hs.get_federation_server().on_invite_request(
  221. self.OTHER_SERVER_NAME,
  222. invite_pdu,
  223. "9",
  224. )
  225. )
  226. # stub out do_remotely_reject_invite so that we fall back to a locally-
  227. # generated rejection
  228. with patch.object(
  229. self.hs.get_federation_handler(),
  230. "do_remotely_reject_invite",
  231. side_effect=Exception(),
  232. ):
  233. reject_event_id, _ = self.get_success(
  234. self.hs.get_room_member_handler().remote_reject_invite(
  235. invite_event_id,
  236. txn_id=None,
  237. requester=create_requester("@user:test"),
  238. content={},
  239. )
  240. )
  241. invite_event, reject_event = self.get_success(
  242. self.hs.get_datastores().main.get_events_as_list(
  243. [invite_event_id, reject_event_id]
  244. )
  245. )
  246. # the invited user should be able to see both the invite and the rejection
  247. self.assertEqual(
  248. self.get_success(
  249. filter_events_for_client(
  250. self.hs.get_storage(), "@user:test", [invite_event, reject_event]
  251. )
  252. ),
  253. [invite_event, reject_event],
  254. )
  255. # other users should see neither
  256. self.assertEqual(
  257. self.get_success(
  258. filter_events_for_client(
  259. self.hs.get_storage(), "@other:test", [invite_event, reject_event]
  260. )
  261. ),
  262. [],
  263. )