Skip to content

Commit 1aeff07

Browse files
committed
Pass room_config argument to user_may_create_room spam checker module callback
1 parent 2436512 commit 1aeff07

File tree

5 files changed

+167
-19
lines changed

5 files changed

+167
-19
lines changed

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.x.x: 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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,7 @@ async def create_room(
786786

787787
if not is_requester_admin:
788788
spam_check = await self._spam_checker_module_callbacks.user_may_create_room(
789-
user_id
789+
user_id, config
790790
)
791791
if spam_check != self._spam_checker_module_callbacks.NOT_SPAM:
792792
raise SynapseError(

synapse/module_api/callbacks/spamchecker_callbacks.py

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -120,20 +120,24 @@
120120
]
121121
],
122122
]
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-
]
123+
USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE = Union[
124+
Literal["NOT_SPAM"],
125+
Codes,
126+
# Highly experimental, not officially part of the spamchecker API, may
127+
# disappear without warning depending on the results of ongoing
128+
# experiments.
129+
# Use this to return additional information as part of an error.
130+
Tuple[Codes, JsonDict],
131+
# Deprecated
132+
bool,
133+
]
134+
USER_MAY_CREATE_ROOM_CALLBACK = Union[
135+
Callable[
136+
[str, JsonDict],
137+
Awaitable[USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE],
138+
],
139+
Callable[ # Single argument variant for backwards compatibility
140+
[str], Awaitable[USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE]
137141
],
138142
]
139143
USER_MAY_CREATE_ROOM_ALIAS_CALLBACK = Callable[
@@ -622,16 +626,41 @@ async def user_may_send_3pid_invite(
622626
return self.NOT_SPAM
623627

624628
async def user_may_create_room(
625-
self, userid: str
629+
self, userid: str, room_config: JsonDict
626630
) -> Union[Tuple[Codes, dict], Literal["NOT_SPAM"]]:
627631
"""Checks if a given user may create a room
628632
629633
Args:
630634
userid: The ID of the user attempting to create a room
635+
room_config: The room creation configuration which is the body of the /createRoom request
631636
"""
632637
for callback in self._user_may_create_room_callbacks:
633638
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
634-
res = await delay_cancellation(callback(userid))
639+
checker_args = inspect.signature(callback)
640+
# Also ensure backwards compatibility with spam checker callbacks
641+
# that don't expect the room_config argument.
642+
if len(checker_args.parameters) == 2:
643+
callback_with_requester_id = cast(
644+
Callable[
645+
[str, JsonDict],
646+
Awaitable[USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE],
647+
],
648+
callback,
649+
)
650+
# We make a copy of the config to ensure the spam checker cannot modify it.
651+
res = await delay_cancellation(
652+
callback_with_requester_id(userid, room_config.copy())
653+
)
654+
else:
655+
callback_without_requester_id = cast(
656+
Callable[
657+
[str], Awaitable[USER_MAY_CREATE_ROOM_CALLBACK_RETURN_VALUE]
658+
],
659+
callback,
660+
)
661+
res = await delay_cancellation(
662+
callback_without_requester_id(userid)
663+
)
635664
if res is True or res is self.NOT_SPAM:
636665
continue
637666
elif res is False:
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
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.rest import admin, login, room
20+
from synapse.server import HomeServer
21+
from synapse.types import Codes, JsonDict
22+
from synapse.util import Clock
23+
24+
from tests.server import FakeChannel
25+
from tests.unittest import HomeserverTestCase
26+
27+
28+
class SpamCheckerTestCase(HomeserverTestCase):
29+
servlets = [
30+
room.register_servlets,
31+
admin.register_servlets,
32+
login.register_servlets,
33+
]
34+
35+
def prepare(
36+
self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
37+
) -> None:
38+
self._module_api = homeserver.get_module_api()
39+
self.user_id = self.register_user("user", "password")
40+
self.token = self.login("user", "password")
41+
42+
def create_room(self, content: JsonDict) -> FakeChannel:
43+
channel = self.make_request(
44+
"POST",
45+
"/_matrix/client/r0/createRoom",
46+
content,
47+
access_token=self.token,
48+
)
49+
50+
return channel
51+
52+
def test_may_user_create_room(self) -> None:
53+
"""Test that the may_user_create_room callback is called when a user
54+
creates a room, and that it receives the correct parameters.
55+
"""
56+
57+
async def user_may_create_room(
58+
user_id: str, room_config: JsonDict
59+
) -> Union[Literal["NOT_SPAM"], Codes]:
60+
self.last_room_config = room_config
61+
self.last_user_id = user_id
62+
return "NOT_SPAM"
63+
64+
self._module_api.register_spam_checker_callbacks(
65+
user_may_create_room=user_may_create_room
66+
)
67+
68+
channel = self.create_room({"foo": "baa"})
69+
self.assertEqual(channel.code, 200)
70+
self.assertEqual(self.last_user_id, self.user_id)
71+
self.assertEqual(self.last_room_config["foo"], "baa")
72+
73+
def test_may_user_create_room_disallowed(self) -> None:
74+
"""Test that the codes response from may_user_create_room callback is respected
75+
and returned via the API.
76+
"""
77+
78+
async def user_may_create_room(
79+
user_id: str, room_config: JsonDict
80+
) -> Union[Literal["NOT_SPAM"], Codes]:
81+
self.last_room_config = room_config
82+
self.last_user_id = user_id
83+
return Codes.UNAUTHORIZED
84+
85+
self._module_api.register_spam_checker_callbacks(
86+
user_may_create_room=user_may_create_room
87+
)
88+
89+
channel = self.create_room({"foo": "baa"})
90+
self.assertEqual(channel.code, 403)
91+
self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED)
92+
self.assertEqual(self.last_user_id, self.user_id)
93+
self.assertEqual(self.last_room_config["foo"], "baa")
94+
95+
def test_may_user_create_room_compatibility(self) -> None:
96+
"""Test that the may_user_create_room callback is called when a user
97+
creates a room for a module that uses the old callback signature
98+
(without the `room_config` parameter)
99+
"""
100+
101+
async def user_may_create_room(
102+
user_id: str,
103+
) -> Union[Literal["NOT_SPAM"], Codes]:
104+
self.last_user_id = user_id
105+
return "NOT_SPAM"
106+
107+
self._module_api.register_spam_checker_callbacks(
108+
user_may_create_room=user_may_create_room
109+
)
110+
111+
channel = self.create_room({"foo": "baa"})
112+
self.assertEqual(channel.code, 200)

0 commit comments

Comments
 (0)