test_redaction.py 15 KB

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