From 4737a7fd11060935279c0ed12c2eb27ab830d03d Mon Sep 17 00:00:00 2001 From: Brendan Abolivier Date: Mon, 6 Dec 2021 11:23:04 +0100 Subject: [PATCH] Remove DomainRuleChecker module (#113) The module has now moved to /~https://github.com/matrix-org/synapse-domain-rule-checker __Note to ops__: To deploy this change, the module needs to be installed in addition to Synapse (from the aforementioned repo, or the PyPI project mentioned its readme). The configuration doesn't change besides a) `default` is renamed into `can_invite_if_not_in_domain_mapping` and b) the module's configuration has moved to the `modules` section of the configuration file (though that was already the case as of /~https://github.com/matrix-org/synapse-dinsic/pull/108). --- synapse/rulecheck/__init__.py | 0 synapse/rulecheck/domain_rule_checker.py | 230 ------------- tests/rulecheck/__init__.py | 14 - tests/rulecheck/test_domainrulecheck.py | 414 ----------------------- 4 files changed, 658 deletions(-) delete mode 100644 synapse/rulecheck/__init__.py delete mode 100644 synapse/rulecheck/domain_rule_checker.py delete mode 100644 tests/rulecheck/__init__.py delete mode 100644 tests/rulecheck/test_domainrulecheck.py diff --git a/synapse/rulecheck/__init__.py b/synapse/rulecheck/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/synapse/rulecheck/domain_rule_checker.py b/synapse/rulecheck/domain_rule_checker.py deleted file mode 100644 index b4d659b06a..0000000000 --- a/synapse/rulecheck/domain_rule_checker.py +++ /dev/null @@ -1,230 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2018 New Vector Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -from typing import Optional - -from synapse.api.constants import EventTypes, Membership -from synapse.config._base import ConfigError -from synapse.module_api import ModuleApi - -logger = logging.getLogger(__name__) - - -class DomainRuleChecker(object): - """ - A re-implementation of the SpamChecker that prevents users in one domain from - inviting users in other domains to rooms, based on a configuration. - - Takes a config in the format: - - spam_checker: - module: "rulecheck.DomainRuleChecker" - config: - domain_mapping: - "inviter_domain": [ "invitee_domain_permitted", "other_domain_permitted" ] - "other_inviter_domain": [ "invitee_domain_permitted" ] - default: False - - # Only let local users join rooms if they were explicitly invited. - can_only_join_rooms_with_invite: false - - # Only let local users create rooms if they are inviting only one - # other user, and that user matches the rules above. - can_only_create_one_to_one_rooms: false - - # Only let local users invite during room creation, regardless of the - # domain mapping rules above. - can_only_invite_during_room_creation: false - - # Prevent local users from inviting users from certain domains to - # rooms published in the room directory. - domains_prevented_from_being_invited_to_published_rooms: [] - - # Allow third party invites - can_invite_by_third_party_id: true - - Don't forget to consider if you can invite users from your own domain. - """ - - def __init__(self, config, api: ModuleApi): - self.domain_mapping = config["domain_mapping"] or {} - self.default = config["default"] - - self.can_only_join_rooms_with_invite = config.get( - "can_only_join_rooms_with_invite", False - ) - self.can_only_invite_during_room_creation = config.get( - "can_only_invite_during_room_creation", False - ) - self.can_invite_by_third_party_id = config.get( - "can_invite_by_third_party_id", True - ) - self.domains_prevented_from_being_invited_to_published_rooms = config.get( - "domains_prevented_from_being_invited_to_published_rooms", [] - ) - - self._api = api - - self._api.register_spam_checker_callbacks( - user_may_invite=self.user_may_invite, - user_may_send_3pid_invite=self.user_may_send_3pid_invite, - user_may_join_room=self.user_may_join_room, - ) - - async def _is_new_room(self, room_id: str) -> bool: - """Checks if the room provided looks new according to its state. - - The module will consider a room to look new if the only m.room.member events in - its state are either for the room's creator (i.e. its join event) or invites sent - by the room's creator. - - Args: - room_id: The ID of the room to check. - - Returns: - Whether the room looks new. - """ - state_event_filter = [ - (EventTypes.Create, None), - (EventTypes.Member, None), - ] - - events = await self._api.get_room_state(room_id, state_event_filter) - - room_creator = events[(EventTypes.Create, "")].sender - - for key, event in events.items(): - if key[0] == EventTypes.Create: - continue - - if key[1] != room_creator: - if ( - event.sender != room_creator - and event.membership != Membership.INVITE - ): - return False - - return True - - async def user_may_invite( - self, - inviter_userid: str, - invitee_userid: str, - room_id: str, - ) -> bool: - """Implements the user_may_invite spam checker callback.""" - return await self._user_may_invite( - room_id=room_id, - inviter_userid=inviter_userid, - invitee_userid=invitee_userid, - ) - - async def user_may_send_3pid_invite( - self, - inviter_userid: str, - medium: str, - address: str, - room_id: str, - ) -> bool: - """Implements the user_may_send_3pid_invite spam checker callback.""" - return await self._user_may_invite( - room_id=room_id, - inviter_userid=inviter_userid, - invitee_userid=None, - ) - - async def _user_may_invite( - self, - room_id: str, - inviter_userid: str, - invitee_userid: Optional[str], - ) -> bool: - """Processes any incoming invite, both normal Matrix invites and 3PID ones, and - check if they should be allowed. - - Args: - room_id: The ID of the room the invite is happening in. - inviter_userid: The MXID of the user sending the invite. - invitee_userid: The MXID of the user being invited, or None if this is a 3PID - invite (in which case no MXID exists for this user yet). - - Returns: - Whether the invite can be allowed to go through. - """ - new_room = await self._is_new_room(room_id) - - if self.can_only_invite_during_room_creation and not new_room: - return False - - # If invitee_userid is None, then this means this is a 3PID invite (without a - # bound MXID), so we allow it unless the configuration mandates blocking all 3PID - # invites. - if invitee_userid is None: - return self.can_invite_by_third_party_id - - inviter_domain = self._get_domain_from_id(inviter_userid) - invitee_domain = self._get_domain_from_id(invitee_userid) - - if inviter_domain not in self.domain_mapping: - return self.default - - published_room = ( - await self._api.public_room_list_manager.room_is_in_public_room_list( - room_id - ) - ) - - if ( - published_room - and invitee_domain - in self.domains_prevented_from_being_invited_to_published_rooms - ): - return False - - return invitee_domain in self.domain_mapping[inviter_domain] - - async def user_may_join_room(self, userid, room_id, is_invited): - """Implements the user_may_join_room spam checker callback.""" - if self.can_only_join_rooms_with_invite and not is_invited: - return False - - return True - - @staticmethod - def parse_config(config): - """Checks whether required fields exist in the provided configuration for the - module. - """ - if "default" in config: - return config - else: - raise ConfigError("No default set for spam_config DomainRuleChecker") - - @staticmethod - def _get_domain_from_id(mxid): - """Parses a string and returns the domain part of the mxid. - - Args: - mxid (str): a valid mxid - - Returns: - str: the domain part of the mxid - - """ - idx = mxid.find(":") - if idx == -1: - raise Exception("Invalid ID: %r" % (mxid,)) - return mxid[idx + 1 :] diff --git a/tests/rulecheck/__init__.py b/tests/rulecheck/__init__.py deleted file mode 100644 index a354d38ca8..0000000000 --- a/tests/rulecheck/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2018 New Vector Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/tests/rulecheck/test_domainrulecheck.py b/tests/rulecheck/test_domainrulecheck.py deleted file mode 100644 index ab4023a72f..0000000000 --- a/tests/rulecheck/test_domainrulecheck.py +++ /dev/null @@ -1,414 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2018 New Vector Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import json -from typing import Optional - -import attr - -import synapse.rest.admin -from synapse.api.constants import EventTypes -from synapse.config._base import ConfigError -from synapse.rest.client import login, room -from synapse.rulecheck.domain_rule_checker import DomainRuleChecker - -from tests import unittest - - -@attr.s(auto_attribs=True) -class MockEvent: - """Mock of an event, only implementing the fields the DomainRuleChecker module will - use. - """ - - sender: str - membership: Optional[str] = None - - -@attr.s(auto_attribs=True) -class MockPublicRoomListManager: - """Mock of a synapse.module_api.PublicRoomListManager, only implementing the method - the DomainRuleChecker module will use. - """ - - _published: bool - - async def room_is_in_public_room_list(self, room_id: str) -> bool: - return self._published - - -@attr.s(auto_attribs=True) -class MockModuleApi: - """Mock of a synapse.module_api.ModuleApi, only implementing the methods the - DomainRuleChecker module will use. - """ - - _new_room: bool - _published: bool - - def register_spam_checker_callbacks(self, *args, **kwargs): - """Don't fail when the module tries to register its callbacks.""" - pass - - @property - def public_room_list_manager(self): - """Returns a mock public room list manager. We could in theory return a Mock with - a return value of make_awaitable(self._published), but local testing seems to show - this doesn't work on all versions of Python. - """ - return MockPublicRoomListManager(self._published) - - async def get_room_state(self, *args, **kwargs): - """Mocks the ModuleApi's get_room_state method, by returning mock events. The - number of events depends on whether we're testing for a new room or not (if the - room is not new it will have an extra user joined to it). - """ - state = { - (EventTypes.Create, ""): MockEvent("room_creator"), - (EventTypes.Member, "room_creator"): MockEvent("room_creator", "join"), - (EventTypes.Member, "invitee"): MockEvent("room_creator", "invite"), - } - - if not self._new_room: - state[(EventTypes.Member, "joinee")] = MockEvent("joinee", "join") - - return state - - -# We use a HomeserverTestCase despite not using the homeserver itself because we need a -# reactor to run asynchronous code. -class DomainRuleCheckerTestCase(unittest.HomeserverTestCase): - def _test_user_may_invite( - self, - config, - inviter, - invitee, - new_room, - published, - ) -> bool: - check = DomainRuleChecker(config, MockModuleApi(new_room, published)) - return self.get_success(check.user_may_invite(inviter, invitee, "room")) - - def test_allowed(self): - config = { - "default": False, - "domain_mapping": { - "source_one": ["target_one", "target_two"], - "source_two": ["target_two"], - }, - "domains_prevented_from_being_invited_to_published_rooms": ["target_two"], - } - - self.assertTrue( - self._test_user_may_invite( - config, - "test:source_one", - "test:target_one", - False, - False, - ), - ) - - self.assertTrue( - self._test_user_may_invite( - config, - "test:source_one", - "test:target_two", - False, - False, - ), - ) - - self.assertTrue( - self._test_user_may_invite( - config, - "test:source_two", - "test:target_two", - False, - False, - ), - ) - - # User can invite internal user to a published room - self.assertTrue( - self._test_user_may_invite( - config, - "test:source_one", - "test1:target_one", - False, - True, - ), - ) - - # User can invite external user to a non-published room - self.assertTrue( - self._test_user_may_invite( - config, - "test:source_one", - "test:target_two", - False, - False, - ), - ) - - def test_disallowed(self): - config = { - "default": True, - "domain_mapping": { - "source_one": ["target_one", "target_two"], - "source_two": ["target_two"], - "source_four": [], - }, - } - - self.assertFalse( - self._test_user_may_invite( - config, - "test:source_one", - "test:target_three", - False, - False, - ) - ) - self.assertFalse( - self._test_user_may_invite( - config, - "test:source_two", - "test:target_three", - False, - False, - ) - ) - self.assertFalse( - self._test_user_may_invite( - config, "test:source_two", "test:target_one", False, False - ) - ) - self.assertFalse( - self._test_user_may_invite( - config, "test:source_four", "test:target_one", False, False - ) - ) - - # User cannot invite external user to a published room - self.assertTrue( - self._test_user_may_invite( - config, "test:source_one", "test:target_two", False, True - ) - ) - - def test_default_allow(self): - config = { - "default": True, - "domain_mapping": { - "source_one": ["target_one", "target_two"], - "source_two": ["target_two"], - }, - } - - self.assertTrue( - self._test_user_may_invite( - config, - "test:source_three", - "test:target_one", - False, - False, - ) - ) - - def test_default_deny(self): - config = { - "default": False, - "domain_mapping": { - "source_one": ["target_one", "target_two"], - "source_two": ["target_two"], - }, - } - - self.assertFalse( - self._test_user_may_invite( - config, - "test:source_three", - "test:target_one", - False, - False, - ) - ) - - def test_config_parse(self): - config = { - "default": False, - "domain_mapping": { - "source_one": ["target_one", "target_two"], - "source_two": ["target_two"], - }, - } - self.assertEquals(config, DomainRuleChecker.parse_config(config)) - - def test_config_parse_failure(self): - config = { - "domain_mapping": { - "source_one": ["target_one", "target_two"], - "source_two": ["target_two"], - } - } - self.assertRaises(ConfigError, DomainRuleChecker.parse_config, config) - - -class DomainRuleCheckerRoomTestCase(unittest.HomeserverTestCase): - servlets = [ - synapse.rest.admin.register_servlets_for_client_rest_resource, - room.register_servlets, - login.register_servlets, - ] - - hijack_auth = False - - def make_homeserver(self, reactor, clock): - config = self.default_config() - config["trusted_third_party_id_servers"] = ["localhost"] - - config["modules"] = [ - { - "module": "synapse.rulecheck.domain_rule_checker.DomainRuleChecker", - "config": { - "default": True, - "domain_mapping": {}, - "can_only_join_rooms_with_invite": True, - "can_only_create_one_to_one_rooms": True, - "can_only_invite_during_room_creation": True, - "can_invite_by_third_party_id": False, - }, - } - ] - - hs = self.setup_test_homeserver(config=config) - - module_api = hs.get_module_api() - for module, config in hs.config.modules.loaded_modules: - module(config=config, api=module_api) - - return hs - - def prepare(self, reactor, clock, hs): - self.admin_user_id = self.register_user("admin_user", "pass", admin=True) - self.admin_access_token = self.login("admin_user", "pass") - - self.normal_user_id = self.register_user("normal_user", "pass", admin=False) - self.normal_access_token = self.login("normal_user", "pass") - - self.other_user_id = self.register_user("other_user", "pass", admin=False) - - def test_admin_can_create_room(self): - channel = self._create_room(self.admin_access_token) - assert channel.result["code"] == b"200", channel.result - - def test_cannot_join_public_room(self): - channel = self._create_room(self.admin_access_token) - assert channel.result["code"] == b"200", channel.result - - room_id = channel.json_body["room_id"] - - self.helper.join( - room_id, self.normal_user_id, tok=self.normal_access_token, expect_code=403 - ) - - def test_can_join_invited_room(self): - channel = self._create_room(self.admin_access_token) - assert channel.result["code"] == b"200", channel.result - - room_id = channel.json_body["room_id"] - - self.helper.invite( - room_id, - src=self.admin_user_id, - targ=self.normal_user_id, - tok=self.admin_access_token, - ) - - self.helper.join( - room_id, self.normal_user_id, tok=self.normal_access_token, expect_code=200 - ) - - def test_cannot_invite(self): - channel = self._create_room(self.admin_access_token) - assert channel.result["code"] == b"200", channel.result - - room_id = channel.json_body["room_id"] - - self.helper.invite( - room_id, - src=self.admin_user_id, - targ=self.normal_user_id, - tok=self.admin_access_token, - ) - - self.helper.join( - room_id, self.normal_user_id, tok=self.normal_access_token, expect_code=200 - ) - - self.helper.invite( - room_id, - src=self.normal_user_id, - targ=self.other_user_id, - tok=self.normal_access_token, - expect_code=403, - ) - - def test_cannot_3pid_invite(self): - """Test that unbound 3pid invites get rejected.""" - channel = self._create_room(self.admin_access_token) - assert channel.result["code"] == b"200", channel.result - - room_id = channel.json_body["room_id"] - - self.helper.invite( - room_id, - src=self.admin_user_id, - targ=self.normal_user_id, - tok=self.admin_access_token, - ) - - self.helper.join( - room_id, self.normal_user_id, tok=self.normal_access_token, expect_code=200 - ) - - self.helper.invite( - room_id, - src=self.normal_user_id, - targ=self.other_user_id, - tok=self.normal_access_token, - expect_code=403, - ) - - channel = self.make_request( - "POST", - "rooms/%s/invite" % (room_id), - {"address": "foo@bar.com", "medium": "email", "id_server": "localhost"}, - access_token=self.normal_access_token, - ) - self.assertEqual(channel.code, 403, channel.result["body"]) - - def _create_room(self, token, content=None): - path = "/_matrix/client/r0/createRoom?access_token=%s" % (token,) - - channel = self.make_request( - "POST", - path, - content=json.dumps(content or {}).encode("utf8"), - ) - - return channel