test_third_party_rules.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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. import threading
  16. from typing import Dict
  17. from mock import Mock
  18. from synapse.events import EventBase
  19. from synapse.module_api import ModuleApi
  20. from synapse.rest import admin
  21. from synapse.rest.client.v1 import login, room
  22. from synapse.types import Requester, StateMap
  23. from tests import unittest
  24. thread_local = threading.local()
  25. class ThirdPartyRulesTestModule:
  26. def __init__(self, config: Dict, module_api: ModuleApi):
  27. # keep a record of the "current" rules module, so that the test can patch
  28. # it if desired.
  29. thread_local.rules_module = self
  30. self.module_api = module_api
  31. async def on_create_room(
  32. self, requester: Requester, config: dict, is_requester_admin: bool
  33. ):
  34. return True
  35. async def check_event_allowed(self, event: EventBase, state: StateMap[EventBase]):
  36. return True
  37. @staticmethod
  38. def parse_config(config):
  39. return config
  40. def current_rules_module() -> ThirdPartyRulesTestModule:
  41. return thread_local.rules_module
  42. class ThirdPartyRulesTestCase(unittest.HomeserverTestCase):
  43. servlets = [
  44. admin.register_servlets,
  45. login.register_servlets,
  46. room.register_servlets,
  47. ]
  48. def default_config(self):
  49. config = super().default_config()
  50. config["third_party_event_rules"] = {
  51. "module": __name__ + ".ThirdPartyRulesTestModule",
  52. "config": {},
  53. }
  54. return config
  55. def prepare(self, reactor, clock, homeserver):
  56. # Create a user and room to play with during the tests
  57. self.user_id = self.register_user("kermit", "monkey")
  58. self.tok = self.login("kermit", "monkey")
  59. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  60. def test_third_party_rules(self):
  61. """Tests that a forbidden event is forbidden from being sent, but an allowed one
  62. can be sent.
  63. """
  64. # patch the rules module with a Mock which will return False for some event
  65. # types
  66. async def check(ev, state):
  67. return ev.type != "foo.bar.forbidden"
  68. callback = Mock(spec=[], side_effect=check)
  69. current_rules_module().check_event_allowed = callback
  70. channel = self.make_request(
  71. "PUT",
  72. "/_matrix/client/r0/rooms/%s/send/foo.bar.allowed/1" % self.room_id,
  73. {},
  74. access_token=self.tok,
  75. )
  76. self.assertEquals(channel.result["code"], b"200", channel.result)
  77. callback.assert_called_once()
  78. # there should be various state events in the state arg: do some basic checks
  79. state_arg = callback.call_args[0][1]
  80. for k in (("m.room.create", ""), ("m.room.member", self.user_id)):
  81. self.assertIn(k, state_arg)
  82. ev = state_arg[k]
  83. self.assertEqual(ev.type, k[0])
  84. self.assertEqual(ev.state_key, k[1])
  85. channel = self.make_request(
  86. "PUT",
  87. "/_matrix/client/r0/rooms/%s/send/foo.bar.forbidden/2" % self.room_id,
  88. {},
  89. access_token=self.tok,
  90. )
  91. self.assertEquals(channel.result["code"], b"403", channel.result)
  92. def test_cannot_modify_event(self):
  93. """cannot accidentally modify an event before it is persisted"""
  94. # first patch the event checker so that it will try to modify the event
  95. async def check(ev: EventBase, state):
  96. ev.content = {"x": "y"}
  97. return True
  98. current_rules_module().check_event_allowed = check
  99. # now send the event
  100. channel = self.make_request(
  101. "PUT",
  102. "/_matrix/client/r0/rooms/%s/send/modifyme/1" % self.room_id,
  103. {"x": "x"},
  104. access_token=self.tok,
  105. )
  106. self.assertEqual(channel.result["code"], b"500", channel.result)
  107. def test_modify_event(self):
  108. """The module can return a modified version of the event"""
  109. # first patch the event checker so that it will modify the event
  110. async def check(ev: EventBase, state):
  111. d = ev.get_dict()
  112. d["content"] = {"x": "y"}
  113. return d
  114. current_rules_module().check_event_allowed = check
  115. # now send the event
  116. channel = self.make_request(
  117. "PUT",
  118. "/_matrix/client/r0/rooms/%s/send/modifyme/1" % self.room_id,
  119. {"x": "x"},
  120. access_token=self.tok,
  121. )
  122. self.assertEqual(channel.result["code"], b"200", channel.result)
  123. event_id = channel.json_body["event_id"]
  124. # ... and check that it got modified
  125. channel = self.make_request(
  126. "GET",
  127. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  128. access_token=self.tok,
  129. )
  130. self.assertEqual(channel.result["code"], b"200", channel.result)
  131. ev = channel.json_body
  132. self.assertEqual(ev["content"]["x"], "y")
  133. def test_send_event(self):
  134. """Tests that the module can send an event into a room via the module api"""
  135. content = {
  136. "msgtype": "m.text",
  137. "body": "Hello!",
  138. }
  139. event_dict = {
  140. "room_id": self.room_id,
  141. "type": "m.room.message",
  142. "content": content,
  143. "sender": self.user_id,
  144. }
  145. event = self.get_success(
  146. current_rules_module().module_api.create_and_send_event_into_room(
  147. event_dict
  148. )
  149. ) # type: EventBase
  150. self.assertEquals(event.sender, self.user_id)
  151. self.assertEquals(event.room_id, self.room_id)
  152. self.assertEquals(event.type, "m.room.message")
  153. self.assertEquals(event.content, content)