Skip to content

Commit 28f21b4

Browse files
authored
Add user_may_send_state_event callback to spam checker module API (#18455)
1 parent 379356c commit 28f21b4

File tree

6 files changed

+200
-0
lines changed

6 files changed

+200
-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 v1.132.0_
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
@@ -107,6 +107,7 @@
107107
USER_MAY_JOIN_ROOM_CALLBACK,
108108
USER_MAY_PUBLISH_ROOM_CALLBACK,
109109
USER_MAY_SEND_3PID_INVITE_CALLBACK,
110+
USER_MAY_SEND_STATE_EVENT_CALLBACK,
110111
SpamCheckerModuleApiCallbacks,
111112
)
112113
from synapse.module_api.callbacks.third_party_event_rules_callbacks import (
@@ -315,6 +316,7 @@ def register_spam_checker_callbacks(
315316
USER_MAY_CREATE_ROOM_ALIAS_CALLBACK
316317
] = None,
317318
user_may_publish_room: Optional[USER_MAY_PUBLISH_ROOM_CALLBACK] = None,
319+
user_may_send_state_event: Optional[USER_MAY_SEND_STATE_EVENT_CALLBACK] = None,
318320
check_username_for_spam: Optional[CHECK_USERNAME_FOR_SPAM_CALLBACK] = None,
319321
check_registration_for_spam: Optional[
320322
CHECK_REGISTRATION_FOR_SPAM_CALLBACK
@@ -339,6 +341,7 @@ def register_spam_checker_callbacks(
339341
check_registration_for_spam=check_registration_for_spam,
340342
check_media_file_for_spam=check_media_file_for_spam,
341343
check_login_for_spam=check_login_for_spam,
344+
user_may_send_state_event=user_may_send_state_event,
342345
)
343346

344347
def register_account_validity_callbacks(

synapse/module_api/callbacks/spamchecker_callbacks.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,20 @@
173173
]
174174
],
175175
]
176+
USER_MAY_SEND_STATE_EVENT_CALLBACK = Callable[
177+
[str, str, str, str, JsonDict],
178+
Awaitable[
179+
Union[
180+
Literal["NOT_SPAM"],
181+
Codes,
182+
# Highly experimental, not officially part of the spamchecker API, may
183+
# disappear without warning depending on the results of ongoing
184+
# experiments.
185+
# Use this to return additional information as part of an error.
186+
Tuple[Codes, JsonDict],
187+
]
188+
],
189+
]
176190
CHECK_USERNAME_FOR_SPAM_CALLBACK = Union[
177191
Callable[[UserProfile], Awaitable[bool]],
178192
Callable[[UserProfile, str], Awaitable[bool]],
@@ -337,6 +351,9 @@ def __init__(self, hs: "synapse.server.HomeServer") -> None:
337351
USER_MAY_SEND_3PID_INVITE_CALLBACK
338352
] = []
339353
self._user_may_create_room_callbacks: List[USER_MAY_CREATE_ROOM_CALLBACK] = []
354+
self._user_may_send_state_event_callbacks: List[
355+
USER_MAY_SEND_STATE_EVENT_CALLBACK
356+
] = []
340357
self._user_may_create_room_alias_callbacks: List[
341358
USER_MAY_CREATE_ROOM_ALIAS_CALLBACK
342359
] = []
@@ -372,6 +389,7 @@ def register_callbacks(
372389
] = None,
373390
check_media_file_for_spam: Optional[CHECK_MEDIA_FILE_FOR_SPAM_CALLBACK] = None,
374391
check_login_for_spam: Optional[CHECK_LOGIN_FOR_SPAM_CALLBACK] = None,
392+
user_may_send_state_event: Optional[USER_MAY_SEND_STATE_EVENT_CALLBACK] = None,
375393
) -> None:
376394
"""Register callbacks from module for each hook."""
377395
if check_event_for_spam is not None:
@@ -396,6 +414,11 @@ def register_callbacks(
396414
if user_may_create_room is not None:
397415
self._user_may_create_room_callbacks.append(user_may_create_room)
398416

417+
if user_may_send_state_event is not None:
418+
self._user_may_send_state_event_callbacks.append(
419+
user_may_send_state_event,
420+
)
421+
399422
if user_may_create_room_alias is not None:
400423
self._user_may_create_room_alias_callbacks.append(
401424
user_may_create_room_alias,
@@ -683,6 +706,40 @@ async def user_may_create_room(
683706

684707
return self.NOT_SPAM
685708

709+
async def user_may_send_state_event(
710+
self,
711+
user_id: str,
712+
room_id: str,
713+
event_type: str,
714+
state_key: str,
715+
content: JsonDict,
716+
) -> Union[Tuple[Codes, dict], Literal["NOT_SPAM"]]:
717+
"""Checks if a given user may create a room with a given visibility
718+
Args:
719+
user_id: The ID of the user attempting to create a room
720+
room_id: The ID of the room that the event will be sent to
721+
event_type: The type of the state event
722+
state_key: The state key of the state event
723+
content: The content of the state event
724+
"""
725+
for callback in self._user_may_send_state_event_callbacks:
726+
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
727+
# We make a copy of the content to ensure that the spam checker cannot modify it.
728+
res = await delay_cancellation(
729+
callback(user_id, room_id, event_type, state_key, deepcopy(content))
730+
)
731+
if res is self.NOT_SPAM:
732+
continue
733+
elif isinstance(res, synapse.api.errors.Codes):
734+
return res, {}
735+
else:
736+
logger.warning(
737+
"Module returned invalid value, rejecting room creation as spam"
738+
)
739+
return synapse.api.errors.Codes.FORBIDDEN, {}
740+
741+
return self.NOT_SPAM
742+
686743
async def user_may_create_room_alias(
687744
self, userid: str, room_alias: RoomAlias
688745
) -> 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+
user_id=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
@@ -153,3 +153,92 @@ async def user_may_create_room(
153153
channel = self.create_room({"foo": "baa"})
154154
self.assertEqual(channel.code, 200)
155155
self.assertEqual(self.last_user_id, self.user_id)
156+
157+
def test_user_may_send_state_event(self) -> None:
158+
"""Test that the user_may_send_state_event callback is called when a state event
159+
is sent, and that it receives the correct parameters.
160+
"""
161+
162+
async def user_may_send_state_event(
163+
user_id: str,
164+
room_id: str,
165+
event_type: str,
166+
state_key: str,
167+
content: JsonDict,
168+
) -> Union[Literal["NOT_SPAM"], Codes]:
169+
self.last_user_id = user_id
170+
self.last_room_id = room_id
171+
self.last_event_type = event_type
172+
self.last_state_key = state_key
173+
self.last_content = content
174+
return "NOT_SPAM"
175+
176+
self._module_api.register_spam_checker_callbacks(
177+
user_may_send_state_event=user_may_send_state_event
178+
)
179+
180+
channel = self.create_room({})
181+
self.assertEqual(channel.code, 200)
182+
183+
room_id = channel.json_body["room_id"]
184+
185+
event_type = "test.event.type"
186+
state_key = "test.state.key"
187+
channel = self.make_request(
188+
"PUT",
189+
"/_matrix/client/r0/rooms/%s/state/%s/%s"
190+
% (
191+
room_id,
192+
event_type,
193+
state_key,
194+
),
195+
content={"foo": "bar"},
196+
access_token=self.token,
197+
)
198+
199+
self.assertEqual(channel.code, 200)
200+
self.assertEqual(self.last_user_id, self.user_id)
201+
self.assertEqual(self.last_room_id, room_id)
202+
self.assertEqual(self.last_event_type, event_type)
203+
self.assertEqual(self.last_state_key, state_key)
204+
self.assertEqual(self.last_content, {"foo": "bar"})
205+
206+
def test_user_may_send_state_event_disallows(self) -> None:
207+
"""Test that the user_may_send_state_event callback is called when a state event
208+
is sent, and that the response is honoured.
209+
"""
210+
211+
async def user_may_send_state_event(
212+
user_id: str,
213+
room_id: str,
214+
event_type: str,
215+
state_key: str,
216+
content: JsonDict,
217+
) -> Union[Literal["NOT_SPAM"], Codes]:
218+
return Codes.FORBIDDEN
219+
220+
self._module_api.register_spam_checker_callbacks(
221+
user_may_send_state_event=user_may_send_state_event
222+
)
223+
224+
channel = self.create_room({})
225+
self.assertEqual(channel.code, 200)
226+
227+
room_id = channel.json_body["room_id"]
228+
229+
event_type = "test.event.type"
230+
state_key = "test.state.key"
231+
channel = self.make_request(
232+
"PUT",
233+
"/_matrix/client/r0/rooms/%s/state/%s/%s"
234+
% (
235+
room_id,
236+
event_type,
237+
state_key,
238+
),
239+
content={"foo": "bar"},
240+
access_token=self.token,
241+
)
242+
243+
self.assertEqual(channel.code, 403)
244+
self.assertEqual(channel.json_body["errcode"], Codes.FORBIDDEN)

0 commit comments

Comments
 (0)