test_retention.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 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. from mock import Mock
  16. from synapse.api.constants import EventTypes
  17. from synapse.rest import admin
  18. from synapse.rest.client.v1 import login, room
  19. from synapse.visibility import filter_events_for_client
  20. from tests import unittest
  21. one_hour_ms = 3600000
  22. one_day_ms = one_hour_ms * 24
  23. class RetentionTestCase(unittest.HomeserverTestCase):
  24. servlets = [
  25. admin.register_servlets,
  26. login.register_servlets,
  27. room.register_servlets,
  28. ]
  29. def make_homeserver(self, reactor, clock):
  30. config = self.default_config()
  31. config["retention"] = {
  32. "enabled": True,
  33. "default_policy": {
  34. "min_lifetime": one_day_ms,
  35. "max_lifetime": one_day_ms * 3,
  36. },
  37. "allowed_lifetime_min": one_day_ms,
  38. "allowed_lifetime_max": one_day_ms * 3,
  39. }
  40. self.hs = self.setup_test_homeserver(config=config)
  41. return self.hs
  42. def prepare(self, reactor, clock, homeserver):
  43. self.user_id = self.register_user("user", "password")
  44. self.token = self.login("user", "password")
  45. self.store = self.hs.get_datastore()
  46. self.serializer = self.hs.get_event_client_serializer()
  47. self.clock = self.hs.get_clock()
  48. def test_retention_event_purged_with_state_event(self):
  49. """Tests that expired events are correctly purged when the room's retention policy
  50. is defined by a state event.
  51. """
  52. room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  53. # Set the room's retention period to 2 days.
  54. lifetime = one_day_ms * 2
  55. self.helper.send_state(
  56. room_id=room_id,
  57. event_type=EventTypes.Retention,
  58. body={"max_lifetime": lifetime},
  59. tok=self.token,
  60. )
  61. self._test_retention_event_purged(room_id, one_day_ms * 1.5)
  62. def test_retention_event_purged_with_state_event_outside_allowed(self):
  63. """Tests that the server configuration can override the policy for a room when
  64. running the purge jobs.
  65. """
  66. room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  67. # Set a max_lifetime higher than the maximum allowed value.
  68. self.helper.send_state(
  69. room_id=room_id,
  70. event_type=EventTypes.Retention,
  71. body={"max_lifetime": one_day_ms * 4},
  72. tok=self.token,
  73. )
  74. # Check that the event is purged after waiting for the maximum allowed duration
  75. # instead of the one specified in the room's policy.
  76. self._test_retention_event_purged(room_id, one_day_ms * 1.5)
  77. # Set a max_lifetime lower than the minimum allowed value.
  78. self.helper.send_state(
  79. room_id=room_id,
  80. event_type=EventTypes.Retention,
  81. body={"max_lifetime": one_hour_ms},
  82. tok=self.token,
  83. )
  84. # Check that the event is purged after waiting for the minimum allowed duration
  85. # instead of the one specified in the room's policy.
  86. self._test_retention_event_purged(room_id, one_day_ms * 0.5)
  87. def test_retention_event_purged_without_state_event(self):
  88. """Tests that expired events are correctly purged when the room's retention policy
  89. is defined by the server's configuration's default retention policy.
  90. """
  91. room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  92. self._test_retention_event_purged(room_id, one_day_ms * 2)
  93. def test_visibility(self):
  94. """Tests that synapse.visibility.filter_events_for_client correctly filters out
  95. outdated events
  96. """
  97. store = self.hs.get_datastore()
  98. storage = self.hs.get_storage()
  99. room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  100. events = []
  101. # Send a first event, which should be filtered out at the end of the test.
  102. resp = self.helper.send(room_id=room_id, body="1", tok=self.token)
  103. # Get the event from the store so that we end up with a FrozenEvent that we can
  104. # give to filter_events_for_client. We need to do this now because the event won't
  105. # be in the database anymore after it has expired.
  106. events.append(self.get_success(store.get_event(resp.get("event_id"))))
  107. # Advance the time by 2 days. We're using the default retention policy, therefore
  108. # after this the first event will still be valid.
  109. self.reactor.advance(one_day_ms * 2 / 1000)
  110. # Send another event, which shouldn't get filtered out.
  111. resp = self.helper.send(room_id=room_id, body="2", tok=self.token)
  112. valid_event_id = resp.get("event_id")
  113. events.append(self.get_success(store.get_event(valid_event_id)))
  114. # Advance the time by another 2 days. After this, the first event should be
  115. # outdated but not the second one.
  116. self.reactor.advance(one_day_ms * 2 / 1000)
  117. # Run filter_events_for_client with our list of FrozenEvents.
  118. filtered_events = self.get_success(
  119. filter_events_for_client(storage, self.user_id, events)
  120. )
  121. # We should only get one event back.
  122. self.assertEqual(len(filtered_events), 1, filtered_events)
  123. # That event should be the second, not outdated event.
  124. self.assertEqual(filtered_events[0].event_id, valid_event_id, filtered_events)
  125. def _test_retention_event_purged(self, room_id: str, increment: float):
  126. """Run the following test scenario to test the message retention policy support:
  127. 1. Send event 1
  128. 2. Increment time by `increment`
  129. 3. Send event 2
  130. 4. Increment time by `increment`
  131. 5. Check that event 1 has been purged
  132. 6. Check that event 2 has not been purged
  133. 7. Check that state events that were sent before event 1 aren't purged.
  134. The main reason for sending a second event is because currently Synapse won't
  135. purge the latest message in a room because it would otherwise result in a lack of
  136. forward extremities for this room. It's also a good thing to ensure the purge jobs
  137. aren't too greedy and purge messages they shouldn't.
  138. Args:
  139. room_id: The ID of the room to test retention in.
  140. increment: The number of milliseconds to advance the clock each time. Must be
  141. defined so that events in the room aren't purged if they are `increment`
  142. old but are purged if they are `increment * 2` old.
  143. """
  144. # Get the create event to, later, check that we can still access it.
  145. message_handler = self.hs.get_message_handler()
  146. create_event = self.get_success(
  147. message_handler.get_room_data(
  148. self.user_id, room_id, EventTypes.Create, state_key=""
  149. )
  150. )
  151. # Send a first event to the room. This is the event we'll want to be purged at the
  152. # end of the test.
  153. resp = self.helper.send(room_id=room_id, body="1", tok=self.token)
  154. expired_event_id = resp.get("event_id")
  155. # Check that we can retrieve the event.
  156. expired_event = self.get_event(expired_event_id)
  157. self.assertEqual(
  158. expired_event.get("content", {}).get("body"), "1", expired_event
  159. )
  160. # Advance the time.
  161. self.reactor.advance(increment / 1000)
  162. # Send another event. We need this because the purge job won't purge the most
  163. # recent event in the room.
  164. resp = self.helper.send(room_id=room_id, body="2", tok=self.token)
  165. valid_event_id = resp.get("event_id")
  166. # Advance the time again. Now our first event should have expired but our second
  167. # one should still be kept.
  168. self.reactor.advance(increment / 1000)
  169. # Check that the first event has been purged from the database, i.e. that we
  170. # can't retrieve it anymore, because it has expired.
  171. self.get_event(expired_event_id, expect_none=True)
  172. # Check that the event that hasn't expired can still be retrieved.
  173. valid_event = self.get_event(valid_event_id)
  174. self.assertEqual(valid_event.get("content", {}).get("body"), "2", valid_event)
  175. # Check that we can still access state events that were sent before the event that
  176. # has been purged.
  177. self.get_event(room_id, create_event.event_id)
  178. def get_event(self, event_id, expect_none=False):
  179. event = self.get_success(self.store.get_event(event_id, allow_none=True))
  180. if expect_none:
  181. self.assertIsNone(event)
  182. return {}
  183. self.assertIsNotNone(event)
  184. time_now = self.clock.time_msec()
  185. serialized = self.get_success(self.serializer.serialize_event(event, time_now))
  186. return serialized
  187. class RetentionNoDefaultPolicyTestCase(unittest.HomeserverTestCase):
  188. servlets = [
  189. admin.register_servlets,
  190. login.register_servlets,
  191. room.register_servlets,
  192. ]
  193. def make_homeserver(self, reactor, clock):
  194. config = self.default_config()
  195. config["retention"] = {
  196. "enabled": True,
  197. }
  198. mock_federation_client = Mock(spec=["backfill"])
  199. self.hs = self.setup_test_homeserver(
  200. config=config, federation_client=mock_federation_client,
  201. )
  202. return self.hs
  203. def prepare(self, reactor, clock, homeserver):
  204. self.user_id = self.register_user("user", "password")
  205. self.token = self.login("user", "password")
  206. def test_no_default_policy(self):
  207. """Tests that an event doesn't get expired if there is neither a default retention
  208. policy nor a policy specific to the room.
  209. """
  210. room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  211. self._test_retention(room_id)
  212. def test_state_policy(self):
  213. """Tests that an event gets correctly expired if there is no default retention
  214. policy but there's a policy specific to the room.
  215. """
  216. room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  217. # Set the maximum lifetime to 35 days so that the first event gets expired but not
  218. # the second one.
  219. self.helper.send_state(
  220. room_id=room_id,
  221. event_type=EventTypes.Retention,
  222. body={"max_lifetime": one_day_ms * 35},
  223. tok=self.token,
  224. )
  225. self._test_retention(room_id, expected_code_for_first_event=404)
  226. def _test_retention(self, room_id, expected_code_for_first_event=200):
  227. # Send a first event to the room. This is the event we'll want to be purged at the
  228. # end of the test.
  229. resp = self.helper.send(room_id=room_id, body="1", tok=self.token)
  230. first_event_id = resp.get("event_id")
  231. # Check that we can retrieve the event.
  232. expired_event = self.get_event(room_id, first_event_id)
  233. self.assertEqual(
  234. expired_event.get("content", {}).get("body"), "1", expired_event
  235. )
  236. # Advance the time by a month.
  237. self.reactor.advance(one_day_ms * 30 / 1000)
  238. # Send another event. We need this because the purge job won't purge the most
  239. # recent event in the room.
  240. resp = self.helper.send(room_id=room_id, body="2", tok=self.token)
  241. second_event_id = resp.get("event_id")
  242. # Advance the time by another month.
  243. self.reactor.advance(one_day_ms * 30 / 1000)
  244. # Check if the event has been purged from the database.
  245. first_event = self.get_event(
  246. room_id, first_event_id, expected_code=expected_code_for_first_event
  247. )
  248. if expected_code_for_first_event == 200:
  249. self.assertEqual(
  250. first_event.get("content", {}).get("body"), "1", first_event
  251. )
  252. # Check that the event that hasn't been purged can still be retrieved.
  253. second_event = self.get_event(room_id, second_event_id)
  254. self.assertEqual(second_event.get("content", {}).get("body"), "2", second_event)
  255. def get_event(self, room_id, event_id, expected_code=200):
  256. url = "/_matrix/client/r0/rooms/%s/event/%s" % (room_id, event_id)
  257. channel = self.make_request("GET", url, access_token=self.token)
  258. self.assertEqual(channel.code, expected_code, channel.result)
  259. return channel.json_body