test_retention.py 13 KB

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