test_visibility.py 13 KB

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