test_third_party_rules.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # Copyright 2019 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. import threading
  15. from typing import Dict
  16. from unittest.mock import Mock
  17. from synapse.events import EventBase
  18. from synapse.module_api import ModuleApi
  19. from synapse.rest import admin
  20. from synapse.rest.client.v1 import login, room
  21. from synapse.types import Requester, StateMap
  22. from tests import unittest
  23. thread_local = threading.local()
  24. class ThirdPartyRulesTestModule:
  25. def __init__(self, config: Dict, module_api: ModuleApi):
  26. # keep a record of the "current" rules module, so that the test can patch
  27. # it if desired.
  28. thread_local.rules_module = self
  29. self.module_api = module_api
  30. async def on_create_room(
  31. self, requester: Requester, config: dict, is_requester_admin: bool
  32. ):
  33. return True
  34. async def check_event_allowed(self, event: EventBase, state: StateMap[EventBase]):
  35. return True
  36. @staticmethod
  37. def parse_config(config):
  38. return config
  39. def current_rules_module() -> ThirdPartyRulesTestModule:
  40. return thread_local.rules_module
  41. class ThirdPartyRulesTestCase(unittest.HomeserverTestCase):
  42. servlets = [
  43. admin.register_servlets,
  44. login.register_servlets,
  45. room.register_servlets,
  46. ]
  47. def default_config(self):
  48. config = super().default_config()
  49. config["third_party_event_rules"] = {
  50. "module": __name__ + ".ThirdPartyRulesTestModule",
  51. "config": {},
  52. }
  53. return config
  54. def prepare(self, reactor, clock, homeserver):
  55. # Create a user and room to play with during the tests
  56. self.user_id = self.register_user("kermit", "monkey")
  57. self.tok = self.login("kermit", "monkey")
  58. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  59. def test_third_party_rules(self):
  60. """Tests that a forbidden event is forbidden from being sent, but an allowed one
  61. can be sent.
  62. """
  63. # patch the rules module with a Mock which will return False for some event
  64. # types
  65. async def check(ev, state):
  66. return ev.type != "foo.bar.forbidden"
  67. callback = Mock(spec=[], side_effect=check)
  68. current_rules_module().check_event_allowed = callback
  69. channel = self.make_request(
  70. "PUT",
  71. "/_matrix/client/r0/rooms/%s/send/foo.bar.allowed/1" % self.room_id,
  72. {},
  73. access_token=self.tok,
  74. )
  75. self.assertEquals(channel.result["code"], b"200", channel.result)
  76. callback.assert_called_once()
  77. # there should be various state events in the state arg: do some basic checks
  78. state_arg = callback.call_args[0][1]
  79. for k in (("m.room.create", ""), ("m.room.member", self.user_id)):
  80. self.assertIn(k, state_arg)
  81. ev = state_arg[k]
  82. self.assertEqual(ev.type, k[0])
  83. self.assertEqual(ev.state_key, k[1])
  84. channel = self.make_request(
  85. "PUT",
  86. "/_matrix/client/r0/rooms/%s/send/foo.bar.forbidden/2" % self.room_id,
  87. {},
  88. access_token=self.tok,
  89. )
  90. self.assertEquals(channel.result["code"], b"403", channel.result)
  91. def test_cannot_modify_event(self):
  92. """cannot accidentally modify an event before it is persisted"""
  93. # first patch the event checker so that it will try to modify the event
  94. async def check(ev: EventBase, state):
  95. ev.content = {"x": "y"}
  96. return True
  97. current_rules_module().check_event_allowed = check
  98. # now send the event
  99. channel = self.make_request(
  100. "PUT",
  101. "/_matrix/client/r0/rooms/%s/send/modifyme/1" % self.room_id,
  102. {"x": "x"},
  103. access_token=self.tok,
  104. )
  105. self.assertEqual(channel.result["code"], b"500", channel.result)
  106. def test_modify_event(self):
  107. """The module can return a modified version of the event"""
  108. # first patch the event checker so that it will modify the event
  109. async def check(ev: EventBase, state):
  110. d = ev.get_dict()
  111. d["content"] = {"x": "y"}
  112. return d
  113. current_rules_module().check_event_allowed = check
  114. # now send the event
  115. channel = self.make_request(
  116. "PUT",
  117. "/_matrix/client/r0/rooms/%s/send/modifyme/1" % self.room_id,
  118. {"x": "x"},
  119. access_token=self.tok,
  120. )
  121. self.assertEqual(channel.result["code"], b"200", channel.result)
  122. event_id = channel.json_body["event_id"]
  123. # ... and check that it got modified
  124. channel = self.make_request(
  125. "GET",
  126. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  127. access_token=self.tok,
  128. )
  129. self.assertEqual(channel.result["code"], b"200", channel.result)
  130. ev = channel.json_body
  131. self.assertEqual(ev["content"]["x"], "y")
  132. def test_message_edit(self):
  133. """Ensure that the module doesn't cause issues with edited messages."""
  134. # first patch the event checker so that it will modify the event
  135. async def check(ev: EventBase, state):
  136. d = ev.get_dict()
  137. d["content"] = {
  138. "msgtype": "m.text",
  139. "body": d["content"]["body"].upper(),
  140. }
  141. return d
  142. current_rules_module().check_event_allowed = check
  143. # Send an event, then edit it.
  144. channel = self.make_request(
  145. "PUT",
  146. "/_matrix/client/r0/rooms/%s/send/modifyme/1" % self.room_id,
  147. {
  148. "msgtype": "m.text",
  149. "body": "Original body",
  150. },
  151. access_token=self.tok,
  152. )
  153. self.assertEqual(channel.result["code"], b"200", channel.result)
  154. orig_event_id = channel.json_body["event_id"]
  155. channel = self.make_request(
  156. "PUT",
  157. "/_matrix/client/r0/rooms/%s/send/m.room.message/2" % self.room_id,
  158. {
  159. "m.new_content": {"msgtype": "m.text", "body": "Edited body"},
  160. "m.relates_to": {
  161. "rel_type": "m.replace",
  162. "event_id": orig_event_id,
  163. },
  164. "msgtype": "m.text",
  165. "body": "Edited body",
  166. },
  167. access_token=self.tok,
  168. )
  169. self.assertEqual(channel.result["code"], b"200", channel.result)
  170. edited_event_id = channel.json_body["event_id"]
  171. # ... and check that they both got modified
  172. channel = self.make_request(
  173. "GET",
  174. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, orig_event_id),
  175. access_token=self.tok,
  176. )
  177. self.assertEqual(channel.result["code"], b"200", channel.result)
  178. ev = channel.json_body
  179. self.assertEqual(ev["content"]["body"], "ORIGINAL BODY")
  180. channel = self.make_request(
  181. "GET",
  182. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, edited_event_id),
  183. access_token=self.tok,
  184. )
  185. self.assertEqual(channel.result["code"], b"200", channel.result)
  186. ev = channel.json_body
  187. self.assertEqual(ev["content"]["body"], "EDITED BODY")
  188. def test_send_event(self):
  189. """Tests that the module can send an event into a room via the module api"""
  190. content = {
  191. "msgtype": "m.text",
  192. "body": "Hello!",
  193. }
  194. event_dict = {
  195. "room_id": self.room_id,
  196. "type": "m.room.message",
  197. "content": content,
  198. "sender": self.user_id,
  199. }
  200. event = self.get_success(
  201. current_rules_module().module_api.create_and_send_event_into_room(
  202. event_dict
  203. )
  204. ) # type: EventBase
  205. self.assertEquals(event.sender, self.user_id)
  206. self.assertEquals(event.room_id, self.room_id)
  207. self.assertEquals(event.type, "m.room.message")
  208. self.assertEquals(event.content, content)