test_redaction.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. # Copyright 2014-2021 The Matrix.org Foundation C.I.C.
  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 typing import List, Optional
  15. from canonicaljson import json
  16. from synapse.api.constants import EventTypes, Membership
  17. from synapse.api.room_versions import RoomVersions
  18. from synapse.types import RoomID, UserID
  19. from tests import unittest
  20. from tests.utils import create_room
  21. class RedactionTestCase(unittest.HomeserverTestCase):
  22. def default_config(self):
  23. config = super().default_config()
  24. config["redaction_retention_period"] = "30d"
  25. return config
  26. def prepare(self, reactor, clock, hs):
  27. self.store = hs.get_datastores().main
  28. self.storage = hs.get_storage()
  29. self.event_builder_factory = hs.get_event_builder_factory()
  30. self.event_creation_handler = hs.get_event_creation_handler()
  31. self.u_alice = UserID.from_string("@alice:test")
  32. self.u_bob = UserID.from_string("@bob:test")
  33. self.room1 = RoomID.from_string("!abc123:test")
  34. self.get_success(
  35. create_room(hs, self.room1.to_string(), self.u_alice.to_string())
  36. )
  37. self.depth = 1
  38. def inject_room_member(
  39. self,
  40. room,
  41. user,
  42. membership,
  43. replaces_state=None,
  44. extra_content: Optional[dict] = None,
  45. ):
  46. content = {"membership": membership}
  47. content.update(extra_content or {})
  48. builder = self.event_builder_factory.for_room_version(
  49. RoomVersions.V1,
  50. {
  51. "type": EventTypes.Member,
  52. "sender": user.to_string(),
  53. "state_key": user.to_string(),
  54. "room_id": room.to_string(),
  55. "content": content,
  56. },
  57. )
  58. event, context = self.get_success(
  59. self.event_creation_handler.create_new_client_event(builder)
  60. )
  61. self.get_success(self.storage.persistence.persist_event(event, context))
  62. return event
  63. def inject_message(self, room, user, body):
  64. self.depth += 1
  65. builder = self.event_builder_factory.for_room_version(
  66. RoomVersions.V1,
  67. {
  68. "type": EventTypes.Message,
  69. "sender": user.to_string(),
  70. "state_key": user.to_string(),
  71. "room_id": room.to_string(),
  72. "content": {"body": body, "msgtype": "message"},
  73. },
  74. )
  75. event, context = self.get_success(
  76. self.event_creation_handler.create_new_client_event(builder)
  77. )
  78. self.get_success(self.storage.persistence.persist_event(event, context))
  79. return event
  80. def inject_redaction(self, room, event_id, user, reason):
  81. builder = self.event_builder_factory.for_room_version(
  82. RoomVersions.V1,
  83. {
  84. "type": EventTypes.Redaction,
  85. "sender": user.to_string(),
  86. "state_key": user.to_string(),
  87. "room_id": room.to_string(),
  88. "content": {"reason": reason},
  89. "redacts": event_id,
  90. },
  91. )
  92. event, context = self.get_success(
  93. self.event_creation_handler.create_new_client_event(builder)
  94. )
  95. self.get_success(self.storage.persistence.persist_event(event, context))
  96. return event
  97. def test_redact(self):
  98. self.inject_room_member(self.room1, self.u_alice, Membership.JOIN)
  99. msg_event = self.inject_message(self.room1, self.u_alice, "t")
  100. # Check event has not been redacted:
  101. event = self.get_success(self.store.get_event(msg_event.event_id))
  102. self.assertObjectHasAttributes(
  103. {
  104. "type": EventTypes.Message,
  105. "user_id": self.u_alice.to_string(),
  106. "content": {"body": "t", "msgtype": "message"},
  107. },
  108. event,
  109. )
  110. self.assertFalse("redacted_because" in event.unsigned)
  111. # Redact event
  112. reason = "Because I said so"
  113. self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason)
  114. event = self.get_success(self.store.get_event(msg_event.event_id))
  115. self.assertEqual(msg_event.event_id, event.event_id)
  116. self.assertTrue("redacted_because" in event.unsigned)
  117. self.assertObjectHasAttributes(
  118. {
  119. "type": EventTypes.Message,
  120. "user_id": self.u_alice.to_string(),
  121. "content": {},
  122. },
  123. event,
  124. )
  125. self.assertObjectHasAttributes(
  126. {
  127. "type": EventTypes.Redaction,
  128. "user_id": self.u_alice.to_string(),
  129. "content": {"reason": reason},
  130. },
  131. event.unsigned["redacted_because"],
  132. )
  133. def test_redact_join(self):
  134. self.inject_room_member(self.room1, self.u_alice, Membership.JOIN)
  135. msg_event = self.inject_room_member(
  136. self.room1, self.u_bob, Membership.JOIN, extra_content={"blue": "red"}
  137. )
  138. event = self.get_success(self.store.get_event(msg_event.event_id))
  139. self.assertObjectHasAttributes(
  140. {
  141. "type": EventTypes.Member,
  142. "user_id": self.u_bob.to_string(),
  143. "content": {"membership": Membership.JOIN, "blue": "red"},
  144. },
  145. event,
  146. )
  147. self.assertFalse(hasattr(event, "redacted_because"))
  148. # Redact event
  149. reason = "Because I said so"
  150. self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason)
  151. # Check redaction
  152. event = self.get_success(self.store.get_event(msg_event.event_id))
  153. self.assertTrue("redacted_because" in event.unsigned)
  154. self.assertObjectHasAttributes(
  155. {
  156. "type": EventTypes.Member,
  157. "user_id": self.u_bob.to_string(),
  158. "content": {"membership": Membership.JOIN},
  159. },
  160. event,
  161. )
  162. self.assertObjectHasAttributes(
  163. {
  164. "type": EventTypes.Redaction,
  165. "user_id": self.u_alice.to_string(),
  166. "content": {"reason": reason},
  167. },
  168. event.unsigned["redacted_because"],
  169. )
  170. def test_circular_redaction(self):
  171. redaction_event_id1 = "$redaction1_id:test"
  172. redaction_event_id2 = "$redaction2_id:test"
  173. class EventIdManglingBuilder:
  174. def __init__(self, base_builder, event_id):
  175. self._base_builder = base_builder
  176. self._event_id = event_id
  177. async def build(
  178. self,
  179. prev_event_ids: List[str],
  180. auth_event_ids: Optional[List[str]],
  181. depth: Optional[int] = None,
  182. ):
  183. built_event = await self._base_builder.build(
  184. prev_event_ids=prev_event_ids, auth_event_ids=auth_event_ids
  185. )
  186. built_event._event_id = self._event_id
  187. built_event._dict["event_id"] = self._event_id
  188. assert built_event.event_id == self._event_id
  189. return built_event
  190. @property
  191. def room_id(self):
  192. return self._base_builder.room_id
  193. @property
  194. def type(self):
  195. return self._base_builder.type
  196. @property
  197. def internal_metadata(self):
  198. return self._base_builder.internal_metadata
  199. event_1, context_1 = self.get_success(
  200. self.event_creation_handler.create_new_client_event(
  201. EventIdManglingBuilder(
  202. self.event_builder_factory.for_room_version(
  203. RoomVersions.V1,
  204. {
  205. "type": EventTypes.Redaction,
  206. "sender": self.u_alice.to_string(),
  207. "room_id": self.room1.to_string(),
  208. "content": {"reason": "test"},
  209. "redacts": redaction_event_id2,
  210. },
  211. ),
  212. redaction_event_id1,
  213. )
  214. )
  215. )
  216. self.get_success(self.storage.persistence.persist_event(event_1, context_1))
  217. event_2, context_2 = self.get_success(
  218. self.event_creation_handler.create_new_client_event(
  219. EventIdManglingBuilder(
  220. self.event_builder_factory.for_room_version(
  221. RoomVersions.V1,
  222. {
  223. "type": EventTypes.Redaction,
  224. "sender": self.u_alice.to_string(),
  225. "room_id": self.room1.to_string(),
  226. "content": {"reason": "test"},
  227. "redacts": redaction_event_id1,
  228. },
  229. ),
  230. redaction_event_id2,
  231. )
  232. )
  233. )
  234. self.get_success(self.storage.persistence.persist_event(event_2, context_2))
  235. # fetch one of the redactions
  236. fetched = self.get_success(self.store.get_event(redaction_event_id1))
  237. # it should have been redacted
  238. self.assertEqual(fetched.unsigned["redacted_by"], redaction_event_id2)
  239. self.assertEqual(
  240. fetched.unsigned["redacted_because"].event_id, redaction_event_id2
  241. )
  242. def test_redact_censor(self):
  243. """Test that a redacted event gets censored in the DB after a month"""
  244. self.inject_room_member(self.room1, self.u_alice, Membership.JOIN)
  245. msg_event = self.inject_message(self.room1, self.u_alice, "t")
  246. # Check event has not been redacted:
  247. event = self.get_success(self.store.get_event(msg_event.event_id))
  248. self.assertObjectHasAttributes(
  249. {
  250. "type": EventTypes.Message,
  251. "user_id": self.u_alice.to_string(),
  252. "content": {"body": "t", "msgtype": "message"},
  253. },
  254. event,
  255. )
  256. self.assertFalse("redacted_because" in event.unsigned)
  257. # Redact event
  258. reason = "Because I said so"
  259. self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason)
  260. event = self.get_success(self.store.get_event(msg_event.event_id))
  261. self.assertTrue("redacted_because" in event.unsigned)
  262. self.assertObjectHasAttributes(
  263. {
  264. "type": EventTypes.Message,
  265. "user_id": self.u_alice.to_string(),
  266. "content": {},
  267. },
  268. event,
  269. )
  270. event_json = self.get_success(
  271. self.store.db_pool.simple_select_one_onecol(
  272. table="event_json",
  273. keyvalues={"event_id": msg_event.event_id},
  274. retcol="json",
  275. )
  276. )
  277. self.assert_dict(
  278. {"content": {"body": "t", "msgtype": "message"}}, json.loads(event_json)
  279. )
  280. # Advance by 30 days, then advance again to ensure that the looping call
  281. # for updating the stream position gets called and then the looping call
  282. # for the censoring gets called.
  283. self.reactor.advance(60 * 60 * 24 * 31)
  284. self.reactor.advance(60 * 60 * 2)
  285. event_json = self.get_success(
  286. self.store.db_pool.simple_select_one_onecol(
  287. table="event_json",
  288. keyvalues={"event_id": msg_event.event_id},
  289. retcol="json",
  290. )
  291. )
  292. self.assert_dict({"content": {}}, json.loads(event_json))
  293. def test_redact_redaction(self):
  294. """Tests that we can redact a redaction and can fetch it again."""
  295. self.inject_room_member(self.room1, self.u_alice, Membership.JOIN)
  296. msg_event = self.inject_message(self.room1, self.u_alice, "t")
  297. first_redact_event = self.inject_redaction(
  298. self.room1, msg_event.event_id, self.u_alice, "Redacting message"
  299. )
  300. self.inject_redaction(
  301. self.room1,
  302. first_redact_event.event_id,
  303. self.u_alice,
  304. "Redacting redaction",
  305. )
  306. # Now lets jump to the future where we have censored the redaction event
  307. # in the DB.
  308. self.reactor.advance(60 * 60 * 24 * 31)
  309. # We just want to check that fetching the event doesn't raise an exception.
  310. self.get_success(
  311. self.store.get_event(first_redact_event.event_id, allow_none=True)
  312. )
  313. def test_store_redacted_redaction(self):
  314. """Tests that we can store a redacted redaction."""
  315. self.inject_room_member(self.room1, self.u_alice, Membership.JOIN)
  316. builder = self.event_builder_factory.for_room_version(
  317. RoomVersions.V1,
  318. {
  319. "type": EventTypes.Redaction,
  320. "sender": self.u_alice.to_string(),
  321. "room_id": self.room1.to_string(),
  322. "content": {"reason": "foo"},
  323. },
  324. )
  325. redaction_event, context = self.get_success(
  326. self.event_creation_handler.create_new_client_event(builder)
  327. )
  328. self.get_success(
  329. self.storage.persistence.persist_event(redaction_event, context)
  330. )
  331. # Now lets jump to the future where we have censored the redaction event
  332. # in the DB.
  333. self.reactor.advance(60 * 60 * 24 * 31)
  334. # We just want to check that fetching the event doesn't raise an exception.
  335. self.get_success(
  336. self.store.get_event(redaction_event.event_id, allow_none=True)
  337. )