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

Commit 468dd05

Browse files
committed
Uniformize spam-checker API, part 2: check_event_for_spam
Signed-off-by: David Teller <[email protected]>
1 parent 19d83e9 commit 468dd05

File tree

6 files changed

+93
-28
lines changed

6 files changed

+93
-28
lines changed

changelog.d/12808.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Update to `check_event_for_spam`. Deprecate the current callback signature, replace it with a new signature that is both less ambiguous (replacing booleans with explicit allow/block) and more powerful (ability to return explicit error codes).

docs/modules/spam_checker_callbacks.md

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,29 @@ The available spam checker callbacks are:
1111
### `check_event_for_spam`
1212

1313
_First introduced in Synapse v1.37.0_
14+
_Signature extended to support Allow and Code in Synapse v1.60.0_
15+
_Boolean return value deprecated in Synapse v1.60.0_
1416

1517
```python
16-
async def check_event_for_spam(event: "synapse.events.EventBase") -> Union[bool, str]
18+
async def check_event_for_spam(event: "synapse.events.EventBase") -> Union[Allow, Code, DEPRECATED_STR, DEPRECATED_BOOL]
1719
```
1820

19-
Called when receiving an event from a client or via federation. The callback must return
20-
either:
21-
- an error message string, to indicate the event must be rejected because of spam and
22-
give a rejection reason to forward to clients;
23-
- the boolean `True`, to indicate that the event is spammy, but not provide further details; or
24-
- the booelan `False`, to indicate that the event is not considered spammy.
21+
Called when receiving an event from a client or via federation. The callback must return either:
22+
- `synapse.spam_checker_api.ALLOW`, to allow the operation. Other callbacks
23+
may still decide to reject it.
24+
- `synapse.api.errors.Code` to reject the operation with an error code. In case
25+
of doubt, `Code.FORBIDDEN` is a good error code.
26+
- (deprecated) a `str` to reject the operation and specify an error message. Note that clients
27+
typically will not localize the error message to the user's preferred locale.
28+
- (deprecated) on `False`, behave as `ALLOW`. Deprecated as confusing, as some
29+
callbacks in expect `True` to allow and others `True` to reject.
30+
- (deprecated) on `True`, behave as `Code.FORBIDDEN`. Deprecated as confusing, as
31+
some callbacks in expect `True` to allow and others `True` to reject.
2532

2633
If multiple modules implement this callback, they will be considered in order. If a
27-
callback returns `False`, Synapse falls through to the next one. The value of the first
28-
callback that does not return `False` will be used. If this happens, Synapse will not call
29-
any of the subsequent implementations of this callback.
34+
callback returns `ALLOW`, Synapse falls through to the next one. The value of the
35+
first callback that does not return `ALLOW` will be used. If this happens, Synapse
36+
will not call any of the subsequent implementations of this callback.
3037

3138
### `user_may_join_room`
3239

synapse/events/spamcheck.py

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,10 @@
2727
Union,
2828
)
2929

30+
from synapse.api.errors import Codes
3031
from synapse.rest.media.v1._base import FileInfo
3132
from synapse.rest.media.v1.media_storage import ReadableFileWrapper
32-
from synapse.spam_checker_api import RegistrationBehaviour
33+
from synapse.spam_checker_api import ALLOW, Allow, Decision, RegistrationBehaviour
3334
from synapse.types import RoomAlias, UserProfile
3435
from synapse.util.async_helpers import delay_cancellation, maybe_awaitable
3536
from synapse.util.metrics import Measure
@@ -40,9 +41,16 @@
4041

4142
logger = logging.getLogger(__name__)
4243

44+
45+
# A boolean returned value, kept for backwards compatibility but deprecated.
46+
DEPRECATED_BOOL = bool
47+
48+
# A string returned value, kept for backwards compatibility but deprecated.
49+
DEPRECATED_STR = str
50+
4351
CHECK_EVENT_FOR_SPAM_CALLBACK = Callable[
4452
["synapse.events.EventBase"],
45-
Awaitable[Union[bool, str]],
53+
Awaitable[Union[Allow, Codes, DEPRECATED_BOOL, DEPRECATED_STR]],
4654
]
4755
USER_MAY_JOIN_ROOM_CALLBACK = Callable[[str, str, bool], Awaitable[bool]]
4856
USER_MAY_INVITE_CALLBACK = Callable[[str, str, str], Awaitable[bool]]
@@ -244,7 +252,7 @@ def register_callbacks(
244252

245253
async def check_event_for_spam(
246254
self, event: "synapse.events.EventBase"
247-
) -> Union[bool, str]:
255+
) -> Union[Decision, str]:
248256
"""Checks if a given event is considered "spammy" by this server.
249257
250258
If the server considers an event spammy, then it will be rejected if
@@ -255,18 +263,36 @@ async def check_event_for_spam(
255263
event: the event to be checked
256264
257265
Returns:
258-
True or a string if the event is spammy. If a string is returned it
259-
will be used as the error message returned to the user.
266+
- on `ALLOW`, the event is considered good (non-spammy) and should
267+
be let through. Other spamcheck filters may still reject it.
268+
- on `Code`, the event is considered spammy and is rejected with a specific
269+
error message/code.
270+
- on `str`, the event is considered spammy and the string is used as error
271+
message. This usage is generally discouraged as it doesn't support
272+
internationalization.
260273
"""
261274
for callback in self._check_event_for_spam_callbacks:
262275
with Measure(
263276
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
264277
):
265-
res: Union[bool, str] = await delay_cancellation(callback(event))
266-
if res:
267-
return res
268-
269-
return False
278+
res: Union[
279+
Decision, DEPRECATED_STR, DEPRECATED_BOOL
280+
] = await delay_cancellation(callback(event))
281+
if res is False or res is ALLOW:
282+
# This spam-checker accepts the event.
283+
# Other spam-checkers may reject it, though.
284+
continue
285+
elif res is True:
286+
# This spam-checker rejects the event with deprecated
287+
# return value `True`
288+
return Codes.FORBIDDEN
289+
else:
290+
# This spam-checker rejects the event either with a `str`
291+
# or with a `Codes`. In either case, we stop here.
292+
return res
293+
294+
# No spam-checker has rejected the event, let it pass.
295+
return ALLOW
270296

271297
async def user_may_join_room(
272298
self, user_id: str, room_id: str, is_invited: bool

synapse/federation/federation_base.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import logging
1616
from typing import TYPE_CHECKING
1717

18+
import synapse
1819
from synapse.api.constants import MAX_DEPTH, EventContentFields, EventTypes, Membership
1920
from synapse.api.errors import Codes, SynapseError
2021
from synapse.api.room_versions import EventFormatVersions, RoomVersion
@@ -98,9 +99,9 @@ async def _check_sigs_and_hash(
9899
)
99100
return redacted_event
100101

101-
result = await self.spam_checker.check_event_for_spam(pdu)
102+
spam_check = await self.spam_checker.check_event_for_spam(pdu)
102103

103-
if result:
104+
if spam_check is not synapse.spam_checker_api.ALLOW:
104105
logger.warning("Event contains spam, soft-failing %s", pdu.event_id)
105106
# we redact (to save disk space) as well as soft-failing (to stop
106107
# using the event in prev_events).

synapse/handlers/message.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
from twisted.internet.interfaces import IDelayedCall
2525

26+
import synapse
2627
from synapse import event_auth
2728
from synapse.api.constants import (
2829
EventContentFields,
@@ -885,11 +886,11 @@ async def create_and_send_nonmember_event(
885886
event.sender,
886887
)
887888

888-
spam_error = await self.spam_checker.check_event_for_spam(event)
889-
if spam_error:
890-
if not isinstance(spam_error, str):
891-
spam_error = "Spam is not permitted here"
892-
raise SynapseError(403, spam_error, Codes.FORBIDDEN)
889+
spam_check = await self.spam_checker.check_event_for_spam(event)
890+
if spam_check is not synapse.spam_checker_api.ALLOW:
891+
raise SynapseError(
892+
403, "This message had been rejected as probable spam", spam_check
893+
)
893894

894895
ev = await self.handle_new_client_event(
895896
requester=requester,

synapse/spam_checker_api/__init__.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,42 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
from enum import Enum
15+
from typing import NewType, Union
16+
17+
from synapse.api.errors import Codes
1518

1619

1720
class RegistrationBehaviour(Enum):
1821
"""
19-
Enum to define whether a registration request should allowed, denied, or shadow-banned.
22+
Enum to define whether a registration request should be allowed, denied, or shadow-banned.
2023
"""
2124

2225
ALLOW = "allow"
2326
SHADOW_BAN = "shadow_ban"
2427
DENY = "deny"
28+
29+
30+
# Define a strongly-typed singleton value `ALLOW`.
31+
32+
# Private NewType, to make sure that nobody outside this module
33+
# defines an instance of `Allow`.
34+
_Allow = NewType("_Allow", str)
35+
36+
# Public NewType, to let the rest of the code mention type `Allow`.
37+
Allow = NewType("Allow", _Allow)
38+
39+
ALLOW = Allow(_Allow("Allow"))
40+
"""
41+
Return this constant to allow a message to pass.
42+
43+
This is the ONLY legal value of type `Allow`.
44+
"""
45+
46+
Decision = Union[Allow, Codes]
47+
"""
48+
Union to define whether a request should be allowed or rejected.
49+
50+
To accept a request, return `ALLOW`.
51+
52+
To reject a request without any specific information, use `Codes.FORBIDDEN`.
53+
"""

0 commit comments

Comments
 (0)