Skip to content

Commit bbe0144

Browse files
committed
Add user_may_send_state_event callback to spam checker module API
1 parent 64b557c commit bbe0144

File tree

6 files changed

+197
-0
lines changed

6 files changed

+197
-0
lines changed

changelog.d/18455.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add user_may_send_state_event callback to spam checker module API.

docs/modules/spam_checker_callbacks.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,36 @@ be used. If this happens, Synapse will not call any of the subsequent implementa
246246
this callback.
247247

248248

249+
### `user_may_send_state_event`
250+
251+
_First introduced in Synapse vX.X.X_
252+
253+
```python
254+
async def user_may_send_state_event(user_id: str, room_id: str, event_type: str, state_key: str, content: JsonDict) -> Union["synapse.module_api.NOT_SPAM", "synapse.module_api.errors.Codes"]
255+
```
256+
257+
Called when processing a request to [send state events](https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3roomsroomidstateeventtypestatekey) to a room.
258+
259+
The arguments passed to this callback are:
260+
261+
* `user_id`: The Matrix user ID of the user (e.g. `@alice:example.com`) sending the state event.
262+
* `room_id`: The ID of the room that the requested state event is being sent to.
263+
* `event_type`: The requested type of event.
264+
* `state_key`: The requested state key.
265+
* `content`: The requested event contents.
266+
267+
The callback must return one of:
268+
- `synapse.module_api.NOT_SPAM`, to allow the operation. Other callbacks may still
269+
decide to reject it.
270+
- `synapse.module_api.errors.Codes` to reject the operation with an error code. In case
271+
of doubt, `synapse.module_api.errors.Codes.FORBIDDEN` is a good error code.
272+
273+
If multiple modules implement this callback, they will be considered in order. If a
274+
callback returns `synapse.module_api.NOT_SPAM`, Synapse falls through to the next one.
275+
The value of the first callback that does not return `synapse.module_api.NOT_SPAM` will
276+
be used. If this happens, Synapse will not call any of the subsequent implementations of
277+
this callback.
278+
249279

250280
### `check_username_for_spam`
251281

synapse/module_api/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
USER_MAY_JOIN_ROOM_CALLBACK,
104104
USER_MAY_PUBLISH_ROOM_CALLBACK,
105105
USER_MAY_SEND_3PID_INVITE_CALLBACK,
106+
USER_MAY_SEND_STATE_EVENT_CALLBACK,
106107
SpamCheckerModuleApiCallbacks,
107108
)
108109
from synapse.module_api.callbacks.third_party_event_rules_callbacks import (
@@ -311,6 +312,7 @@ def register_spam_checker_callbacks(
311312
USER_MAY_CREATE_ROOM_ALIAS_CALLBACK
312313
] = None,
313314
user_may_publish_room: Optional[USER_MAY_PUBLISH_ROOM_CALLBACK] = None,
315+
user_may_send_state_event: Optional[USER_MAY_SEND_STATE_EVENT_CALLBACK] = None,
314316
check_username_for_spam: Optional[CHECK_USERNAME_FOR_SPAM_CALLBACK] = None,
315317
check_registration_for_spam: Optional[
316318
CHECK_REGISTRATION_FOR_SPAM_CALLBACK
@@ -335,6 +337,7 @@ def register_spam_checker_callbacks(
335337
check_registration_for_spam=check_registration_for_spam,
336338
check_media_file_for_spam=check_media_file_for_spam,
337339
check_login_for_spam=check_login_for_spam,
340+
user_may_send_state_event=user_may_send_state_event,
338341
)
339342

340343
def register_account_validity_callbacks(

synapse/module_api/callbacks/spamchecker_callbacks.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,20 @@
172172
]
173173
],
174174
]
175+
USER_MAY_SEND_STATE_EVENT_CALLBACK = Callable[
176+
[str, str, str, str, JsonDict],
177+
Awaitable[
178+
Union[
179+
Literal["NOT_SPAM"],
180+
Codes,
181+
# Highly experimental, not officially part of the spamchecker API, may
182+
# disappear without warning depending on the results of ongoing
183+
# experiments.
184+
# Use this to return additional information as part of an error.
185+
Tuple[Codes, JsonDict],
186+
]
187+
],
188+
]
175189
CHECK_USERNAME_FOR_SPAM_CALLBACK = Union[
176190
Callable[[UserProfile], Awaitable[bool]],
177191
Callable[[UserProfile, str], Awaitable[bool]],
@@ -336,6 +350,9 @@ def __init__(self, hs: "synapse.server.HomeServer") -> None:
336350
USER_MAY_SEND_3PID_INVITE_CALLBACK
337351
] = []
338352
self._user_may_create_room_callbacks: List[USER_MAY_CREATE_ROOM_CALLBACK] = []
353+
self._user_may_send_state_event_callbacks: List[
354+
USER_MAY_SEND_STATE_EVENT_CALLBACK
355+
] = []
339356
self._user_may_create_room_alias_callbacks: List[
340357
USER_MAY_CREATE_ROOM_ALIAS_CALLBACK
341358
] = []
@@ -371,6 +388,7 @@ def register_callbacks(
371388
] = None,
372389
check_media_file_for_spam: Optional[CHECK_MEDIA_FILE_FOR_SPAM_CALLBACK] = None,
373390
check_login_for_spam: Optional[CHECK_LOGIN_FOR_SPAM_CALLBACK] = None,
391+
user_may_send_state_event: Optional[USER_MAY_SEND_STATE_EVENT_CALLBACK] = None,
374392
) -> None:
375393
"""Register callbacks from module for each hook."""
376394
if check_event_for_spam is not None:
@@ -395,6 +413,11 @@ def register_callbacks(
395413
if user_may_create_room is not None:
396414
self._user_may_create_room_callbacks.append(user_may_create_room)
397415

416+
if user_may_send_state_event is not None:
417+
self._user_may_send_state_event_callbacks.append(
418+
user_may_send_state_event,
419+
)
420+
398421
if user_may_create_room_alias is not None:
399422
self._user_may_create_room_alias_callbacks.append(
400423
user_may_create_room_alias,
@@ -682,6 +705,37 @@ async def user_may_create_room(
682705

683706
return self.NOT_SPAM
684707

708+
async def user_may_send_state_event(
709+
self,
710+
userid: str,
711+
room_id: str,
712+
event_type: str,
713+
state_key: str,
714+
content: JsonDict,
715+
) -> Union[Tuple[Codes, dict], Literal["NOT_SPAM"]]:
716+
"""Checks if a given user may create a room with a given visibility
717+
Args:
718+
userid: The ID of the user attempting to create a room
719+
visibility: The visibility of the room to be created
720+
"""
721+
for callback in self._user_may_send_state_event_callbacks:
722+
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
723+
# We make a copy of the content to ensure that the spam checker cannot modify it.
724+
res = await delay_cancellation(
725+
callback(userid, room_id, event_type, state_key, content.copy())
726+
)
727+
if res is self.NOT_SPAM:
728+
continue
729+
elif isinstance(res, synapse.api.errors.Codes):
730+
return res, {}
731+
else:
732+
logger.warning(
733+
"Module returned invalid value, rejecting room creation as spam"
734+
)
735+
return synapse.api.errors.Codes.FORBIDDEN, {}
736+
737+
return self.NOT_SPAM
738+
685739
async def user_may_create_room_alias(
686740
self, userid: str, room_alias: RoomAlias
687741
) -> Union[Tuple[Codes, dict], Literal["NOT_SPAM"]]:

synapse/rest/client/room.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ def __init__(self, hs: "HomeServer"):
198198
self.delayed_events_handler = hs.get_delayed_events_handler()
199199
self.auth = hs.get_auth()
200200
self._max_event_delay_ms = hs.config.server.max_event_delay_ms
201+
self._spam_checker_module_callbacks = hs.get_module_api_callbacks().spam_checker
201202

202203
def register(self, http_server: HttpServer) -> None:
203204
# /rooms/$roomid/state/$eventtype
@@ -289,6 +290,25 @@ async def on_PUT(
289290

290291
content = parse_json_object_from_request(request)
291292

293+
is_requester_admin = await self.auth.is_server_admin(requester)
294+
if not is_requester_admin:
295+
spam_check = (
296+
await self._spam_checker_module_callbacks.user_may_send_state_event(
297+
userid=requester.user.to_string(),
298+
room_id=room_id,
299+
event_type=event_type,
300+
state_key=state_key,
301+
content=content,
302+
)
303+
)
304+
if spam_check != self._spam_checker_module_callbacks.NOT_SPAM:
305+
raise SynapseError(
306+
403,
307+
"You are not permitted to send the state event",
308+
errcode=spam_check[0],
309+
additional_fields=spam_check[1],
310+
)
311+
292312
origin_server_ts = None
293313
if requester.app_service:
294314
origin_server_ts = parse_integer(request, "ts")

tests/module_api/test_spamchecker.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,92 @@ async def user_may_create_room(
152152

153153
channel = self.create_room({"foo": "baa"})
154154
self.assertEqual(channel.code, 200)
155+
156+
def test_user_may_send_state_event(self) -> None:
157+
"""Test that the user_may_send_state_event callback is called when a state event
158+
is sent, and that it receives the correct parameters.
159+
"""
160+
161+
async def user_may_send_state_event(
162+
user_id: str,
163+
room_id: str,
164+
event_type: str,
165+
state_key: str,
166+
content: JsonDict,
167+
) -> Union[Literal["NOT_SPAM"], Codes]:
168+
self.last_user_id = user_id
169+
self.last_room_id = room_id
170+
self.last_event_type = event_type
171+
self.last_state_key = state_key
172+
self.last_content = content
173+
return "NOT_SPAM"
174+
175+
self._module_api.register_spam_checker_callbacks(
176+
user_may_send_state_event=user_may_send_state_event
177+
)
178+
179+
channel = self.create_room({})
180+
self.assertEqual(channel.code, 200)
181+
182+
room_id = channel.json_body["room_id"]
183+
184+
event_type = "test.event.type"
185+
state_key = "test.state.key"
186+
channel = self.make_request(
187+
"PUT",
188+
"/_matrix/client/r0/rooms/%s/state/%s/%s"
189+
% (
190+
room_id,
191+
event_type,
192+
state_key,
193+
),
194+
content={"foo": "bar"},
195+
access_token=self.token,
196+
)
197+
198+
self.assertEqual(channel.code, 200)
199+
self.assertEqual(self.last_user_id, self.user_id)
200+
self.assertEqual(self.last_room_id, room_id)
201+
self.assertEqual(self.last_event_type, event_type)
202+
self.assertEqual(self.last_state_key, state_key)
203+
self.assertEqual(self.last_content, {"foo": "bar"})
204+
205+
def test_user_may_send_state_event_disallows(self) -> None:
206+
"""Test that the user_may_send_state_event callback is called when a state event
207+
is sent, and that the response is honoured.
208+
"""
209+
210+
async def user_may_send_state_event(
211+
user_id: str,
212+
room_id: str,
213+
event_type: str,
214+
state_key: str,
215+
content: JsonDict,
216+
) -> Union[Literal["NOT_SPAM"], Codes]:
217+
return Codes.FORBIDDEN
218+
219+
self._module_api.register_spam_checker_callbacks(
220+
user_may_send_state_event=user_may_send_state_event
221+
)
222+
223+
channel = self.create_room({})
224+
self.assertEqual(channel.code, 200)
225+
226+
room_id = channel.json_body["room_id"]
227+
228+
event_type = "test.event.type"
229+
state_key = "test.state.key"
230+
channel = self.make_request(
231+
"PUT",
232+
"/_matrix/client/r0/rooms/%s/state/%s/%s"
233+
% (
234+
room_id,
235+
event_type,
236+
state_key,
237+
),
238+
content={"foo": "bar"},
239+
access_token=self.token,
240+
)
241+
242+
self.assertEqual(channel.code, 403)
243+
self.assertEqual(channel.json_body["errcode"], Codes.FORBIDDEN)

0 commit comments

Comments
 (0)