Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 0991a2d

Browse files
Allow ThirdPartyEventRules modules to manipulate public room state (#8292)
This PR allows `ThirdPartyEventRules` modules to view, manipulate and block changes to the state of whether a room is published in the public rooms directory. While the idea of whether a room is in the public rooms list is not kept within an event in the room, `ThirdPartyEventRules` generally deal with controlling which modifications can happen to a room. Public rooms fits within that idea, even if its toggle state isn't controlled through a state event.
1 parent f31f8e6 commit 0991a2d

File tree

8 files changed

+223
-19
lines changed

8 files changed

+223
-19
lines changed

UPGRADE.rst

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,23 @@ for example:
7575
wget https://packages.matrix.org/debian/pool/main/m/matrix-synapse-py3/matrix-synapse-py3_1.3.0+stretch1_amd64.deb
7676
dpkg -i matrix-synapse-py3_1.3.0+stretch1_amd64.deb
7777
78+
Upgrading to v1.22.0
79+
====================
80+
81+
ThirdPartyEventRules breaking changes
82+
-------------------------------------
83+
84+
This release introduces a backwards-incompatible change to modules making use of
85+
``ThirdPartyEventRules`` in Synapse. If you make use of a module defined under the
86+
``third_party_event_rules`` config option, please make sure it is updated to handle
87+
the below change:
88+
89+
The ``http_client`` argument is no longer passed to modules as they are initialised. Instead,
90+
modules are expected to make use of the ``http_client`` property on the ``ModuleApi`` class.
91+
Modules are now passed a ``module_api`` argument during initialisation, which is an instance of
92+
``ModuleApi``. ``ModuleApi`` instances have a ``http_client`` property which acts the same as
93+
the ``http_client`` argument previously passed to ``ThirdPartyEventRules`` modules.
94+
7895
Upgrading to v1.21.0
7996
====================
8097

changelog.d/8292.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Allow `ThirdPartyEventRules` modules to query and manipulate whether a room is in the public rooms directory.

synapse/events/third_party_rules.py

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@
1212
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
15+
from typing import Callable
1516

1617
from synapse.events import EventBase
1718
from synapse.events.snapshot import EventContext
18-
from synapse.types import Requester
19+
from synapse.module_api import ModuleApi
20+
from synapse.types import Requester, StateMap
1921

2022

2123
class ThirdPartyEventRules:
@@ -38,7 +40,7 @@ def __init__(self, hs):
3840

3941
if module is not None:
4042
self.third_party_rules = module(
41-
config=config, http_client=hs.get_simple_http_client()
43+
config=config, module_api=ModuleApi(hs, hs.get_auth_handler()),
4244
)
4345

4446
async def check_event_allowed(
@@ -106,14 +108,51 @@ async def check_threepid_can_be_invited(
106108
if self.third_party_rules is None:
107109
return True
108110

111+
state_events = await self._get_state_map_for_room(room_id)
112+
113+
ret = await self.third_party_rules.check_threepid_can_be_invited(
114+
medium, address, state_events
115+
)
116+
return ret
117+
118+
async def check_visibility_can_be_modified(
119+
self, room_id: str, new_visibility: str
120+
) -> bool:
121+
"""Check if a room is allowed to be published to, or removed from, the public room
122+
list.
123+
124+
Args:
125+
room_id: The ID of the room.
126+
new_visibility: The new visibility state. Either "public" or "private".
127+
128+
Returns:
129+
True if the room's visibility can be modified, False if not.
130+
"""
131+
if self.third_party_rules is None:
132+
return True
133+
134+
check_func = getattr(self.third_party_rules, "check_visibility_can_be_modified")
135+
if not check_func or not isinstance(check_func, Callable):
136+
return True
137+
138+
state_events = await self._get_state_map_for_room(room_id)
139+
140+
return await check_func(room_id, state_events, new_visibility)
141+
142+
async def _get_state_map_for_room(self, room_id: str) -> StateMap[EventBase]:
143+
"""Given a room ID, return the state events of that room.
144+
145+
Args:
146+
room_id: The ID of the room.
147+
148+
Returns:
149+
A dict mapping (event type, state key) to state event.
150+
"""
109151
state_ids = await self.store.get_filtered_current_state_ids(room_id)
110152
room_state_events = await self.store.get_events(state_ids.values())
111153

112154
state_events = {}
113155
for key, event_id in state_ids.items():
114156
state_events[key] = room_state_events[event_id]
115157

116-
ret = await self.third_party_rules.check_threepid_can_be_invited(
117-
medium, address, state_events
118-
)
119-
return ret
158+
return state_events

synapse/handlers/directory.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ def __init__(self, hs):
4646
self.config = hs.config
4747
self.enable_room_list_search = hs.config.enable_room_list_search
4848
self.require_membership = hs.config.require_membership_for_aliases
49+
self.third_party_event_rules = hs.get_third_party_event_rules()
4950

5051
self.federation = hs.get_federation_client()
5152
hs.get_federation_registry().register_query_handler(
@@ -454,6 +455,15 @@ async def edit_published_room_list(
454455
# per alias creation rule?
455456
raise SynapseError(403, "Not allowed to publish room")
456457

458+
# Check if publishing is blocked by a third party module
459+
allowed_by_third_party_rules = await (
460+
self.third_party_event_rules.check_visibility_can_be_modified(
461+
room_id, visibility
462+
)
463+
)
464+
if not allowed_by_third_party_rules:
465+
raise SynapseError(403, "Not allowed to publish room")
466+
457467
await self.store.set_room_is_public(room_id, making_public)
458468

459469
async def edit_published_appservice_room_list(

synapse/handlers/room.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,15 @@ async def create_room(
681681
creator_id=user_id, is_public=is_public, room_version=room_version,
682682
)
683683

684+
# Check whether this visibility value is blocked by a third party module
685+
allowed_by_third_party_rules = await (
686+
self.third_party_event_rules.check_visibility_can_be_modified(
687+
room_id, visibility
688+
)
689+
)
690+
if not allowed_by_third_party_rules:
691+
raise SynapseError(403, "Room visibility value not allowed.")
692+
684693
directory_handler = self.hs.get_handlers().directory_handler
685694
if room_alias:
686695
await directory_handler.create_association(

synapse/module_api/__init__.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,18 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616
import logging
17+
from typing import TYPE_CHECKING
1718

1819
from twisted.internet import defer
1920

21+
from synapse.http.client import SimpleHttpClient
2022
from synapse.http.site import SynapseRequest
2123
from synapse.logging.context import make_deferred_yieldable, run_in_background
2224
from synapse.types import UserID
2325

26+
if TYPE_CHECKING:
27+
from synapse.server import HomeServer
28+
2429
"""
2530
This package defines the 'stable' API which can be used by extension modules which
2631
are loaded into Synapse.
@@ -43,6 +48,27 @@ def __init__(self, hs, auth_handler):
4348
self._auth = hs.get_auth()
4449
self._auth_handler = auth_handler
4550

51+
# We expose these as properties below in order to attach a helpful docstring.
52+
self._http_client = hs.get_simple_http_client() # type: SimpleHttpClient
53+
self._public_room_list_manager = PublicRoomListManager(hs)
54+
55+
@property
56+
def http_client(self):
57+
"""Allows making outbound HTTP requests to remote resources.
58+
59+
An instance of synapse.http.client.SimpleHttpClient
60+
"""
61+
return self._http_client
62+
63+
@property
64+
def public_room_list_manager(self):
65+
"""Allows adding to, removing from and checking the status of rooms in the
66+
public room list.
67+
68+
An instance of synapse.module_api.PublicRoomListManager
69+
"""
70+
return self._public_room_list_manager
71+
4672
def get_user_by_req(self, req, allow_guest=False):
4773
"""Check the access_token provided for a request
4874
@@ -266,3 +292,44 @@ async def complete_sso_login_async(
266292
await self._auth_handler.complete_sso_login(
267293
registered_user_id, request, client_redirect_url,
268294
)
295+
296+
297+
class PublicRoomListManager:
298+
"""Contains methods for adding to, removing from and querying whether a room
299+
is in the public room list.
300+
"""
301+
302+
def __init__(self, hs: "HomeServer"):
303+
self._store = hs.get_datastore()
304+
305+
async def room_is_in_public_room_list(self, room_id: str) -> bool:
306+
"""Checks whether a room is in the public room list.
307+
308+
Args:
309+
room_id: The ID of the room.
310+
311+
Returns:
312+
Whether the room is in the public room list. Returns False if the room does
313+
not exist.
314+
"""
315+
room = await self._store.get_room(room_id)
316+
if not room:
317+
return False
318+
319+
return room.get("is_public", False)
320+
321+
async def add_room_to_public_room_list(self, room_id: str) -> None:
322+
"""Publishes a room to the public room list.
323+
324+
Args:
325+
room_id: The ID of the room.
326+
"""
327+
await self._store.set_room_is_public(room_id, True)
328+
329+
async def remove_room_from_public_room_list(self, room_id: str) -> None:
330+
"""Removes a room from the public room list.
331+
332+
Args:
333+
room_id: The ID of the room.
334+
"""
335+
await self._store.set_room_is_public(room_id, False)

tests/module_api/test_api.py

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,20 @@
1212
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
15-
1615
from synapse.module_api import ModuleApi
16+
from synapse.rest import admin
17+
from synapse.rest.client.v1 import login, room
1718

1819
from tests.unittest import HomeserverTestCase
1920

2021

2122
class ModuleApiTestCase(HomeserverTestCase):
23+
servlets = [
24+
admin.register_servlets,
25+
login.register_servlets,
26+
room.register_servlets,
27+
]
28+
2229
def prepare(self, reactor, clock, homeserver):
2330
self.store = homeserver.get_datastore()
2431
self.module_api = ModuleApi(homeserver, homeserver.get_auth_handler())
@@ -52,3 +59,50 @@ def test_can_register_user(self):
5259
# Check that the displayname was assigned
5360
displayname = self.get_success(self.store.get_profile_displayname("bob"))
5461
self.assertEqual(displayname, "Bobberino")
62+
63+
def test_public_rooms(self):
64+
"""Tests that a room can be added and removed from the public rooms list,
65+
as well as have its public rooms directory state queried.
66+
"""
67+
# Create a user and room to play with
68+
user_id = self.register_user("kermit", "monkey")
69+
tok = self.login("kermit", "monkey")
70+
room_id = self.helper.create_room_as(user_id, tok=tok)
71+
72+
# The room should not currently be in the public rooms directory
73+
is_in_public_rooms = self.get_success(
74+
self.module_api.public_room_list_manager.room_is_in_public_room_list(
75+
room_id
76+
)
77+
)
78+
self.assertFalse(is_in_public_rooms)
79+
80+
# Let's try adding it to the public rooms directory
81+
self.get_success(
82+
self.module_api.public_room_list_manager.add_room_to_public_room_list(
83+
room_id
84+
)
85+
)
86+
87+
# And checking whether it's in there...
88+
is_in_public_rooms = self.get_success(
89+
self.module_api.public_room_list_manager.room_is_in_public_room_list(
90+
room_id
91+
)
92+
)
93+
self.assertTrue(is_in_public_rooms)
94+
95+
# Let's remove it again
96+
self.get_success(
97+
self.module_api.public_room_list_manager.remove_room_from_public_room_list(
98+
room_id
99+
)
100+
)
101+
102+
# Should be gone
103+
is_in_public_rooms = self.get_success(
104+
self.module_api.public_room_list_manager.room_is_in_public_room_list(
105+
room_id
106+
)
107+
)
108+
self.assertFalse(is_in_public_rooms)

tests/rest/client/third_party_rules.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,23 @@
1212
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
15-
1615
from synapse.rest import admin
1716
from synapse.rest.client.v1 import login, room
17+
from synapse.types import Requester
1818

1919
from tests import unittest
2020

2121

2222
class ThirdPartyRulesTestModule:
23-
def __init__(self, config):
23+
def __init__(self, config, *args, **kwargs):
2424
pass
2525

26-
def check_event_allowed(self, event, context):
26+
async def on_create_room(
27+
self, requester: Requester, config: dict, is_requester_admin: bool
28+
):
29+
return True
30+
31+
async def check_event_allowed(self, event, context):
2732
if event.type == "foo.bar.forbidden":
2833
return False
2934
else:
@@ -51,29 +56,31 @@ def make_homeserver(self, reactor, clock):
5156
self.hs = self.setup_test_homeserver(config=config)
5257
return self.hs
5358

59+
def prepare(self, reactor, clock, homeserver):
60+
# Create a user and room to play with during the tests
61+
self.user_id = self.register_user("kermit", "monkey")
62+
self.tok = self.login("kermit", "monkey")
63+
64+
self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
65+
5466
def test_third_party_rules(self):
5567
"""Tests that a forbidden event is forbidden from being sent, but an allowed one
5668
can be sent.
5769
"""
58-
user_id = self.register_user("kermit", "monkey")
59-
tok = self.login("kermit", "monkey")
60-
61-
room_id = self.helper.create_room_as(user_id, tok=tok)
62-
6370
request, channel = self.make_request(
6471
"PUT",
65-
"/_matrix/client/r0/rooms/%s/send/foo.bar.allowed/1" % room_id,
72+
"/_matrix/client/r0/rooms/%s/send/foo.bar.allowed/1" % self.room_id,
6673
{},
67-
access_token=tok,
74+
access_token=self.tok,
6875
)
6976
self.render(request)
7077
self.assertEquals(channel.result["code"], b"200", channel.result)
7178

7279
request, channel = self.make_request(
7380
"PUT",
74-
"/_matrix/client/r0/rooms/%s/send/foo.bar.forbidden/1" % room_id,
81+
"/_matrix/client/r0/rooms/%s/send/foo.bar.forbidden/1" % self.room_id,
7582
{},
76-
access_token=tok,
83+
access_token=self.tok,
7784
)
7885
self.render(request)
7986
self.assertEquals(channel.result["code"], b"403", channel.result)

0 commit comments

Comments
 (0)