Skip to content

Commit fbe7a89

Browse files
authored
Pass room_config argument to user_may_create_room spam checker module callback (#18486)
This PR adds an additional `room_config` argument to the `user_may_create_room` spam checker module API callback. It will continue to work with implementations of `user_may_create_room` that do not expect the additional parameter. A side affect is that on a room upgrade the spam checker callback is called *after* doing some work to calculate the state rather than before. However, I hope that this is acceptable given the relative infrequency of room upgrades.
1 parent 08a0506 commit fbe7a89

File tree

6 files changed

+230
-30
lines changed

6 files changed

+230
-30
lines changed

changelog.d/18486.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Pass room_config argument to user_may_create_room spam checker module callback.

docs/modules/spam_checker_callbacks.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,12 +159,19 @@ _First introduced in Synapse v1.37.0_
159159

160160
_Changed in Synapse v1.62.0: `synapse.module_api.NOT_SPAM` and `synapse.module_api.errors.Codes` can be returned by this callback. Returning a boolean is now deprecated._
161161

162+
_Changed in Synapse v1.132.0: Added the `room_config` argument. Callbacks that only expect a single `user_id` argument are still supported._
163+
162164
```python
163-
async def user_may_create_room(user_id: str) -> Union["synapse.module_api.NOT_SPAM", "synapse.module_api.errors.Codes", bool]
165+
async def user_may_create_room(user_id: str, room_config: synapse.module_api.JsonDict) -> Union["synapse.module_api.NOT_SPAM", "synapse.module_api.errors.Codes", bool]
164166
```
165167

166168
Called when processing a room creation request.
167169

170+
The arguments passed to this callback are:
171+
172+
* `user_id`: The Matrix user ID of the user (e.g. `@alice:example.com`).
173+
* `room_config`: The contents of the body of a [/createRoom request](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3createroom) as a dictionary.
174+
168175
The callback must return one of:
169176
- `synapse.module_api.NOT_SPAM`, to allow the operation. Other callbacks may still
170177
decide to reject it.

docs/spam_checker.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ class ExampleSpamChecker:
6363
async def user_may_invite(self, inviter_userid, invitee_userid, room_id):
6464
return True # allow all invites
6565

66-
async def user_may_create_room(self, userid):
66+
async def user_may_create_room(self, userid, room_config):
6767
return True # allow all room creations
6868

6969
async def user_may_create_room_alias(self, userid, room_alias):

synapse/handlers/room.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -468,17 +468,6 @@ async def clone_existing_room(
468468
"""
469469
user_id = requester.user.to_string()
470470

471-
spam_check = await self._spam_checker_module_callbacks.user_may_create_room(
472-
user_id
473-
)
474-
if spam_check != self._spam_checker_module_callbacks.NOT_SPAM:
475-
raise SynapseError(
476-
403,
477-
"You are not permitted to create rooms",
478-
errcode=spam_check[0],
479-
additional_fields=spam_check[1],
480-
)
481-
482471
creation_content: JsonDict = {
483472
"room_version": new_room_version.identifier,
484473
"predecessor": {"room_id": old_room_id, "event_id": tombstone_event_id},
@@ -585,6 +574,24 @@ async def clone_existing_room(
585574
if current_power_level_int < needed_power_level:
586575
user_power_levels[user_id] = needed_power_level
587576

577+
# We construct what the body of a call to /createRoom would look like for passing
578+
# to the spam checker. We don't include a preset here, as we expect the
579+
# initial state to contain everything we need.
580+
spam_check = await self._spam_checker_module_callbacks.user_may_create_room(
581+
user_id,
582+
{
583+
"creation_content": creation_content,
584+
"initial_state": list(initial_state.items()),
585+
},
586+
)
587+
if spam_check != self._spam_checker_module_callbacks.NOT_SPAM:
588+
raise SynapseError(
589+
403,
590+
"You are not permitted to create rooms",
591+
errcode=spam_check[0],
592+
additional_fields=spam_check[1],
593+
)
594+
588595
await self._send_events_for_new_room(
589596
requester,
590597
new_room_id,
@@ -786,7 +793,7 @@ async def create_room(
786793

787794
if not is_requester_admin:
788795
spam_check = await self._spam_checker_module_callbacks.user_may_create_room(
789-
user_id
796+
user_id, config
790797
)
791798
if spam_check != self._spam_checker_module_callbacks.NOT_SPAM:
792799
raise SynapseError(

synapse/module_api/callbacks/spamchecker_callbacks.py

Lines changed: 46 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import functools
2323
import inspect
2424
import logging
25+
from copy import deepcopy
2526
from typing import (
2627
TYPE_CHECKING,
2728
Any,
@@ -120,20 +121,24 @@
120121
]
121122
],
122123
]
123-
USER_MAY_CREATE_ROOM_CALLBACK = Callable[
124-
[str],
125-
Awaitable[
126-
Union[
127-
Literal["NOT_SPAM"],
128-
Codes,
129-
# Highly experimental, not officially part of the spamchecker API, may
130-
# disappear without warning depending on the results of ongoing
131-
# experiments.
132-
# Use this to return additional information as part of an error.
133-
Tuple[Codes, JsonDict],
134-
# Deprecated
135-
bool,
136-
]
124+
USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE = Union[
125+
Literal["NOT_SPAM"],
126+
Codes,
127+
# Highly experimental, not officially part of the spamchecker API, may
128+
# disappear without warning depending on the results of ongoing
129+
# experiments.
130+
# Use this to return additional information as part of an error.
131+
Tuple[Codes, JsonDict],
132+
# Deprecated
133+
bool,
134+
]
135+
USER_MAY_CREATE_ROOM_CALLBACK = Union[
136+
Callable[
137+
[str, JsonDict],
138+
Awaitable[USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE],
139+
],
140+
Callable[ # Single argument variant for backwards compatibility
141+
[str], Awaitable[USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE]
137142
],
138143
]
139144
USER_MAY_CREATE_ROOM_ALIAS_CALLBACK = Callable[
@@ -622,16 +627,41 @@ async def user_may_send_3pid_invite(
622627
return self.NOT_SPAM
623628

624629
async def user_may_create_room(
625-
self, userid: str
630+
self, userid: str, room_config: JsonDict
626631
) -> Union[Tuple[Codes, dict], Literal["NOT_SPAM"]]:
627632
"""Checks if a given user may create a room
628633
629634
Args:
630635
userid: The ID of the user attempting to create a room
636+
room_config: The room creation configuration which is the body of the /createRoom request
631637
"""
632638
for callback in self._user_may_create_room_callbacks:
633639
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
634-
res = await delay_cancellation(callback(userid))
640+
checker_args = inspect.signature(callback)
641+
# Also ensure backwards compatibility with spam checker callbacks
642+
# that don't expect the room_config argument.
643+
if len(checker_args.parameters) == 2:
644+
callback_with_requester_id = cast(
645+
Callable[
646+
[str, JsonDict],
647+
Awaitable[USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE],
648+
],
649+
callback,
650+
)
651+
# We make a copy of the config to ensure the spam checker cannot modify it.
652+
res = await delay_cancellation(
653+
callback_with_requester_id(userid, deepcopy(room_config))
654+
)
655+
else:
656+
callback_without_requester_id = cast(
657+
Callable[
658+
[str], Awaitable[USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE]
659+
],
660+
callback,
661+
)
662+
res = await delay_cancellation(
663+
callback_without_requester_id(userid)
664+
)
635665
if res is True or res is self.NOT_SPAM:
636666
continue
637667
elif res is False:
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
#
2+
# This file is licensed under the Affero General Public License (AGPL) version 3.
3+
#
4+
# Copyright (C) 2025 New Vector, Ltd
5+
#
6+
# This program is free software: you can redistribute it and/or modify
7+
# it under the terms of the GNU Affero General Public License as
8+
# published by the Free Software Foundation, either version 3 of the
9+
# License, or (at your option) any later version.
10+
#
11+
# See the GNU Affero General Public License for more details:
12+
# <https://www.gnu.org/licenses/agpl-3.0.html>.
13+
#
14+
#
15+
from typing import Literal, Union
16+
17+
from twisted.test.proto_helpers import MemoryReactor
18+
19+
from synapse.config.server import DEFAULT_ROOM_VERSION
20+
from synapse.rest import admin, login, room, room_upgrade_rest_servlet
21+
from synapse.server import HomeServer
22+
from synapse.types import Codes, JsonDict
23+
from synapse.util import Clock
24+
25+
from tests.server import FakeChannel
26+
from tests.unittest import HomeserverTestCase
27+
28+
29+
class SpamCheckerTestCase(HomeserverTestCase):
30+
servlets = [
31+
room.register_servlets,
32+
admin.register_servlets,
33+
login.register_servlets,
34+
room_upgrade_rest_servlet.register_servlets,
35+
]
36+
37+
def prepare(
38+
self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
39+
) -> None:
40+
self._module_api = homeserver.get_module_api()
41+
self.user_id = self.register_user("user", "password")
42+
self.token = self.login("user", "password")
43+
44+
def create_room(self, content: JsonDict) -> FakeChannel:
45+
channel = self.make_request(
46+
"POST",
47+
"/_matrix/client/r0/createRoom",
48+
content,
49+
access_token=self.token,
50+
)
51+
52+
return channel
53+
54+
def test_may_user_create_room(self) -> None:
55+
"""Test that the may_user_create_room callback is called when a user
56+
creates a room, and that it receives the correct parameters.
57+
"""
58+
59+
async def user_may_create_room(
60+
user_id: str, room_config: JsonDict
61+
) -> Union[Literal["NOT_SPAM"], Codes]:
62+
self.last_room_config = room_config
63+
self.last_user_id = user_id
64+
return "NOT_SPAM"
65+
66+
self._module_api.register_spam_checker_callbacks(
67+
user_may_create_room=user_may_create_room
68+
)
69+
70+
channel = self.create_room({"foo": "baa"})
71+
self.assertEqual(channel.code, 200)
72+
self.assertEqual(self.last_user_id, self.user_id)
73+
self.assertEqual(self.last_room_config["foo"], "baa")
74+
75+
def test_may_user_create_room_on_upgrade(self) -> None:
76+
"""Test that the may_user_create_room callback is called when a room is upgraded."""
77+
78+
# First, create a room to upgrade.
79+
channel = self.create_room({"topic": "foo"})
80+
self.assertEqual(channel.code, 200)
81+
room_id = channel.json_body["room_id"]
82+
83+
async def user_may_create_room(
84+
user_id: str, room_config: JsonDict
85+
) -> Union[Literal["NOT_SPAM"], Codes]:
86+
self.last_room_config = room_config
87+
self.last_user_id = user_id
88+
return "NOT_SPAM"
89+
90+
# Register the callback for spam checking.
91+
self._module_api.register_spam_checker_callbacks(
92+
user_may_create_room=user_may_create_room
93+
)
94+
95+
# Now upgrade the room.
96+
channel = self.make_request(
97+
"POST",
98+
f"/_matrix/client/r0/rooms/{room_id}/upgrade",
99+
# This will upgrade a room to the same version, but that's fine.
100+
content={"new_version": DEFAULT_ROOM_VERSION},
101+
access_token=self.token,
102+
)
103+
104+
# Check that the callback was called and the room was upgraded.
105+
self.assertEqual(channel.code, 200)
106+
self.assertEqual(self.last_user_id, self.user_id)
107+
# Check that the initial state received by callback contains the topic event.
108+
self.assertTrue(
109+
any(
110+
event[0][0] == "m.room.topic" and event[1].get("topic") == "foo"
111+
for event in self.last_room_config["initial_state"]
112+
)
113+
)
114+
115+
def test_may_user_create_room_disallowed(self) -> None:
116+
"""Test that the codes response from may_user_create_room callback is respected
117+
and returned via the API.
118+
"""
119+
120+
async def user_may_create_room(
121+
user_id: str, room_config: JsonDict
122+
) -> Union[Literal["NOT_SPAM"], Codes]:
123+
self.last_room_config = room_config
124+
self.last_user_id = user_id
125+
return Codes.UNAUTHORIZED
126+
127+
self._module_api.register_spam_checker_callbacks(
128+
user_may_create_room=user_may_create_room
129+
)
130+
131+
channel = self.create_room({"foo": "baa"})
132+
self.assertEqual(channel.code, 403)
133+
self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED)
134+
self.assertEqual(self.last_user_id, self.user_id)
135+
self.assertEqual(self.last_room_config["foo"], "baa")
136+
137+
def test_may_user_create_room_compatibility(self) -> None:
138+
"""Test that the may_user_create_room callback is called when a user
139+
creates a room for a module that uses the old callback signature
140+
(without the `room_config` parameter)
141+
"""
142+
143+
async def user_may_create_room(
144+
user_id: str,
145+
) -> Union[Literal["NOT_SPAM"], Codes]:
146+
self.last_user_id = user_id
147+
return "NOT_SPAM"
148+
149+
self._module_api.register_spam_checker_callbacks(
150+
user_may_create_room=user_may_create_room
151+
)
152+
153+
channel = self.create_room({"foo": "baa"})
154+
self.assertEqual(channel.code, 200)
155+
self.assertEqual(self.last_user_id, self.user_id)

0 commit comments

Comments
 (0)