From 405951e9c57c59b63bcdcefdc356dbd2bc50174a Mon Sep 17 00:00:00 2001 From: reivilibre Date: Wed, 5 Jan 2022 12:40:23 +0000 Subject: deploy: 9be5aacc2d901f553ec972d0d62738bd42c87037 --- v1.50/modules/account_validity_callbacks.html | 284 +++++++++++++ .../background_update_controller_callbacks.html | 302 ++++++++++++++ v1.50/modules/index.html | 297 +++++++++++++ .../modules/password_auth_provider_callbacks.html | 406 ++++++++++++++++++ v1.50/modules/porting_legacy_module.html | 272 ++++++++++++ v1.50/modules/presence_router_callbacks.html | 337 +++++++++++++++ v1.50/modules/spam_checker_callbacks.html | 463 +++++++++++++++++++++ v1.50/modules/third_party_rules_callbacks.html | 393 +++++++++++++++++ v1.50/modules/writing_a_module.html | 316 ++++++++++++++ 9 files changed, 3070 insertions(+) create mode 100644 v1.50/modules/account_validity_callbacks.html create mode 100644 v1.50/modules/background_update_controller_callbacks.html create mode 100644 v1.50/modules/index.html create mode 100644 v1.50/modules/password_auth_provider_callbacks.html create mode 100644 v1.50/modules/porting_legacy_module.html create mode 100644 v1.50/modules/presence_router_callbacks.html create mode 100644 v1.50/modules/spam_checker_callbacks.html create mode 100644 v1.50/modules/third_party_rules_callbacks.html create mode 100644 v1.50/modules/writing_a_module.html (limited to 'v1.50/modules') diff --git a/v1.50/modules/account_validity_callbacks.html b/v1.50/modules/account_validity_callbacks.html new file mode 100644 index 0000000000..2075e4e186 --- /dev/null +++ b/v1.50/modules/account_validity_callbacks.html @@ -0,0 +1,284 @@ + + + + + + Account validity callbacks - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Account validity callbacks

+

Account validity callbacks allow module developers to add extra steps to verify the +validity on an account, i.e. see if a user can be granted access to their account on the +Synapse instance. Account validity callbacks can be registered using the module API's +register_account_validity_callbacks method.

+

The available account validity callbacks are:

+

is_user_expired

+

First introduced in Synapse v1.39.0

+
async def is_user_expired(user: str) -> Optional[bool]
+
+

Called when processing any authenticated request (except for logout requests). The module +can return a bool to indicate whether the user has expired and should be locked out of +their account, or None if the module wasn't able to figure it out. The user is +represented by their Matrix user ID (e.g. @alice:example.com).

+

If the module returns True, the current request will be denied with the error code +ORG_MATRIX_EXPIRED_ACCOUNT and the HTTP status code 403. Note that this doesn't +invalidate the user's access token.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns None, Synapse falls through to the next one. The value of the first +callback that does not return None will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

on_user_registration

+

First introduced in Synapse v1.39.0

+
async def on_user_registration(user: str) -> None
+
+

Called after successfully registering a user, in case the module needs to perform extra +operations to keep track of them. (e.g. add them to a database table). The user is +represented by their Matrix user ID.

+

If multiple modules implement this callback, Synapse runs them all in order.

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/v1.50/modules/background_update_controller_callbacks.html b/v1.50/modules/background_update_controller_callbacks.html new file mode 100644 index 0000000000..363b161dda --- /dev/null +++ b/v1.50/modules/background_update_controller_callbacks.html @@ -0,0 +1,302 @@ + + + + + + Background update controller callbacks - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Background update controller callbacks

+

Background update controller callbacks allow module developers to control (e.g. rate-limit) +how database background updates are run. A database background update is an operation +Synapse runs on its database in the background after it starts. It's usually used to run +database operations that would take too long if they were run at the same time as schema +updates (which are run on startup) and delay Synapse's startup too much: populating a +table with a big amount of data, adding an index on a big table, deleting superfluous data, +etc.

+

Background update controller callbacks can be registered using the module API's +register_background_update_controller_callbacks method. Only the first module (in order +of appearance in Synapse's configuration file) calling this method can register background +update controller callbacks, subsequent calls are ignored.

+

The available background update controller callbacks are:

+

on_update

+

First introduced in Synapse v1.49.0

+
def on_update(update_name: str, database_name: str, one_shot: bool) -> AsyncContextManager[int]
+
+

Called when about to do an iteration of a background update. The module is given the name +of the update, the name of the database, and a flag to indicate whether the background +update will happen in one go and may take a long time (e.g. creating indices). If this last +argument is set to False, the update will be run in batches.

+

The module must return an async context manager. It will be entered before Synapse runs a +background update; this should return the desired duration of the iteration, in +milliseconds.

+

The context manager will be exited when the iteration completes. Note that the duration +returned by the context manager is a target, and an iteration may take substantially longer +or shorter. If the one_shot flag is set to True, the duration returned is ignored.

+

Note: Unlike most module callbacks in Synapse, this one is synchronous. This is +because asynchronous operations are expected to be run by the async context manager.

+

This callback is required when registering any other background update controller callback.

+

default_batch_size

+

First introduced in Synapse v1.49.0

+
async def default_batch_size(update_name: str, database_name: str) -> int
+
+

Called before the first iteration of a background update, with the name of the update and +of the database. The module must return the number of elements to process in this first +iteration.

+

If this callback is not defined, Synapse will use a default value of 100.

+

min_batch_size

+

First introduced in Synapse v1.49.0

+
async def min_batch_size(update_name: str, database_name: str) -> int
+
+

Called before running a new batch for a background update, with the name of the update and +of the database. The module must return an integer representing the minimum number of +elements to process in this iteration. This number must be at least 1, and is used to +ensure that progress is always made.

+

If this callback is not defined, Synapse will use a default value of 100.

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/v1.50/modules/index.html b/v1.50/modules/index.html new file mode 100644 index 0000000000..fef68a568a --- /dev/null +++ b/v1.50/modules/index.html @@ -0,0 +1,297 @@ + + + + + + Pluggable Modules - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Modules

+

Synapse supports extending its functionality by configuring external modules.

+

Note: When using third-party modules, you effectively allow someone else to run +custom code on your Synapse homeserver. Server admins are encouraged to verify the +provenance of the modules they use on their homeserver and make sure the modules aren't +running malicious code on their instance.

+

Using modules

+

To use a module on Synapse, add it to the modules section of the configuration file:

+
modules:
+  - module: my_super_module.MySuperClass
+    config:
+      do_thing: true
+  - module: my_other_super_module.SomeClass
+    config: {}
+
+

Each module is defined by a path to a Python class as well as a configuration. This +information for a given module should be available in the module's own documentation.

+

Using multiple modules

+

The order in which modules are listed in this section is important. When processing an +action that can be handled by several modules, Synapse will always prioritise the module +that appears first (i.e. is the highest in the list). This means:

+
    +
  • If several modules register the same callback, the callback registered by the module +that appears first is used.
  • +
  • If several modules try to register a handler for the same HTTP path, only the handler +registered by the module that appears first is used. Handlers registered by the other +module(s) are ignored and Synapse will log a warning message about them.
  • +
+

Note that Synapse doesn't allow multiple modules implementing authentication checkers via +the password auth provider feature for the same login type with different fields. If this +happens, Synapse will refuse to start.

+

Current status

+

We are currently in the process of migrating module interfaces to this system. While some +interfaces might be compatible with it, others still require configuring modules in +another part of Synapse's configuration file.

+

Currently, only the following pre-existing interfaces are compatible with this new system:

+
    +
  • spam checker
  • +
  • third-party rules
  • +
  • presence router
  • +
  • password auth providers
  • +
+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/v1.50/modules/password_auth_provider_callbacks.html b/v1.50/modules/password_auth_provider_callbacks.html new file mode 100644 index 0000000000..b68ee18177 --- /dev/null +++ b/v1.50/modules/password_auth_provider_callbacks.html @@ -0,0 +1,406 @@ + + + + + + Password auth provider callbacks - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Password auth provider callbacks

+

Password auth providers offer a way for server administrators to integrate +their Synapse installation with an external authentication system. The callbacks can be +registered by using the Module API's register_password_auth_provider_callbacks method.

+

Callbacks

+

auth_checkers

+

First introduced in Synapse v1.46.0

+
auth_checkers: Dict[Tuple[str, Tuple[str, ...]], Callable]
+
+

A dict mapping from tuples of a login type identifier (such as m.login.password) and a +tuple of field names (such as ("password", "secret_thing")) to authentication checking +callbacks, which should be of the following form:

+
async def check_auth(
+    user: str,
+    login_type: str,
+    login_dict: "synapse.module_api.JsonDict",
+) -> Optional[
+    Tuple[
+        str, 
+        Optional[Callable[["synapse.module_api.LoginResponse"], Awaitable[None]]]
+    ]
+]
+
+

The login type and field names should be provided by the user in the +request to the /login API. The Matrix specification +defines some types, however user defined ones are also allowed.

+

The callback is passed the user field provided by the client (which might not be in +@username:server form), the login type, and a dictionary of login secrets passed by +the client.

+

If the authentication is successful, the module must return the user's Matrix ID (e.g. +@alice:example.com) and optionally a callback to be called with the response to the +/login request. If the module doesn't wish to return a callback, it must return None +instead.

+

If the authentication is unsuccessful, the module must return None.

+

If multiple modules register an auth checker for the same login type but with different +fields, Synapse will refuse to start.

+

If multiple modules register an auth checker for the same login type with the same fields, +then the callbacks will be executed in order, until one returns a Matrix User ID (and +optionally a callback). In that case, the return value of that callback will be accepted +and subsequent callbacks will not be fired. If every callback returns None, then the +authentication fails.

+

check_3pid_auth

+

First introduced in Synapse v1.46.0

+
async def check_3pid_auth(
+    medium: str, 
+    address: str,
+    password: str,
+) -> Optional[
+    Tuple[
+        str, 
+        Optional[Callable[["synapse.module_api.LoginResponse"], Awaitable[None]]]
+    ]
+]
+
+

Called when a user attempts to register or log in with a third party identifier, +such as email. It is passed the medium (eg. email), an address (eg. jdoe@example.com) +and the user's password.

+

If the authentication is successful, the module must return the user's Matrix ID (e.g. +@alice:example.com) and optionally a callback to be called with the response to the /login request. +If the module doesn't wish to return a callback, it must return None instead.

+

If the authentication is unsuccessful, the module must return None.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns None, Synapse falls through to the next one. The value of the first +callback that does not return None will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback. If every callback return None, +the authentication is denied.

+

on_logged_out

+

First introduced in Synapse v1.46.0

+
async def on_logged_out(
+    user_id: str,
+    device_id: Optional[str],
+    access_token: str
+) -> None
+
+

Called during a logout request for a user. It is passed the qualified user ID, the ID of the +deactivated device (if any: access tokens are occasionally created without an associated +device ID), and the (now deactivated) access token.

+

If multiple modules implement this callback, Synapse runs them all in order.

+

Example

+

The example module below implements authentication checkers for two different login types:

+
    +
  • my.login.type +
      +
    • Expects a my_field field to be sent to /login
    • +
    • Is checked by the method: self.check_my_login
    • +
    +
  • +
  • m.login.password (defined in the spec) +
      +
    • Expects a password field to be sent to /login
    • +
    • Is checked by the method: self.check_pass
    • +
    +
  • +
+
from typing import Awaitable, Callable, Optional, Tuple
+
+import synapse
+from synapse import module_api
+
+
+class MyAuthProvider:
+    def __init__(self, config: dict, api: module_api):
+
+        self.api = api
+
+        self.credentials = {
+            "bob": "building",
+            "@scoop:matrix.org": "digging",
+        }
+
+        api.register_password_auth_provider_callbacks(
+            auth_checkers={
+                ("my.login_type", ("my_field",)): self.check_my_login,
+                ("m.login.password", ("password",)): self.check_pass,
+            },
+        )
+
+    async def check_my_login(
+        self,
+        username: str,
+        login_type: str,
+        login_dict: "synapse.module_api.JsonDict",
+    ) -> Optional[
+        Tuple[
+            str,
+            Optional[Callable[["synapse.module_api.LoginResponse"], Awaitable[None]]],
+        ]
+    ]:
+        if login_type != "my.login_type":
+            return None
+
+        if self.credentials.get(username) == login_dict.get("my_field"):
+            return self.api.get_qualified_user_id(username)
+
+    async def check_pass(
+        self,
+        username: str,
+        login_type: str,
+        login_dict: "synapse.module_api.JsonDict",
+    ) -> Optional[
+        Tuple[
+            str,
+            Optional[Callable[["synapse.module_api.LoginResponse"], Awaitable[None]]],
+        ]
+    ]:
+        if login_type != "m.login.password":
+            return None
+
+        if self.credentials.get(username) == login_dict.get("password"):
+            return self.api.get_qualified_user_id(username)
+
+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/v1.50/modules/porting_legacy_module.html b/v1.50/modules/porting_legacy_module.html new file mode 100644 index 0000000000..1ac824b041 --- /dev/null +++ b/v1.50/modules/porting_legacy_module.html @@ -0,0 +1,272 @@ + + + + + + Porting a legacy module to the new interface - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Porting an existing module that uses the old interface

+

In order to port a module that uses Synapse's old module interface, its author needs to:

+
    +
  • ensure the module's callbacks are all asynchronous.
  • +
  • register their callbacks using one or more of the register_[...]_callbacks methods +from the ModuleApi class in the module's __init__ method (see this section +for more info).
  • +
+

Additionally, if the module is packaged with an additional web resource, the module +should register this resource in its __init__ method using the register_web_resource +method from the ModuleApi class (see this section for +more info).

+

There is no longer a get_db_schema_files callback provided for password auth provider modules. Any +changes to the database should now be made by the module using the module API class.

+

The module's author should also update any example in the module's configuration to only +use the new modules section in Synapse's configuration file (see this section +for more info).

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/v1.50/modules/presence_router_callbacks.html b/v1.50/modules/presence_router_callbacks.html new file mode 100644 index 0000000000..eddd9d992c --- /dev/null +++ b/v1.50/modules/presence_router_callbacks.html @@ -0,0 +1,337 @@ + + + + + + Presence router callbacks - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Presence router callbacks

+

Presence router callbacks allow module developers to specify additional users (local or remote) +to receive certain presence updates from local users. Presence router callbacks can be +registered using the module API's register_presence_router_callbacks method.

+

Callbacks

+

The available presence router callbacks are:

+

get_users_for_states

+

First introduced in Synapse v1.42.0

+
async def get_users_for_states(
+    state_updates: Iterable["synapse.api.UserPresenceState"],
+) -> Dict[str, Set["synapse.api.UserPresenceState"]]
+
+

Requires get_interested_users to also be registered

+

Called when processing updates to the presence state of one or more users. This callback can +be used to instruct the server to forward that presence state to specific users. The module +must return a dictionary that maps from Matrix user IDs (which can be local or remote) to the +UserPresenceState changes that they should be forwarded.

+

Synapse will then attempt to send the specified presence updates to each user when possible.

+

If multiple modules implement this callback, Synapse merges all the dictionaries returned +by the callbacks. If multiple callbacks return a dictionary containing the same key, +Synapse concatenates the sets associated with this key from each dictionary.

+

get_interested_users

+

First introduced in Synapse v1.42.0

+
async def get_interested_users(
+    user_id: str
+) -> Union[Set[str], "synapse.module_api.PRESENCE_ALL_USERS"]
+
+

Requires get_users_for_states to also be registered

+

Called when determining which users someone should be able to see the presence state of. This +callback should return complementary results to get_users_for_state or the presence information +may not be properly forwarded.

+

The callback is given the Matrix user ID for a local user that is requesting presence data and +should return the Matrix user IDs of the users whose presence state they are allowed to +query. The returned users can be local or remote.

+

Alternatively the callback can return synapse.module_api.PRESENCE_ALL_USERS +to indicate that the user should receive updates from all known users.

+

If multiple modules implement this callback, they will be considered in order. Synapse +calls each callback one by one, and use a concatenation of all the sets returned by the +callbacks. If one callback returns synapse.module_api.PRESENCE_ALL_USERS, Synapse uses +this value instead. If this happens, Synapse does not call any of the subsequent +implementations of this callback.

+

Example

+

The example below is a module that implements both presence router callbacks, and ensures +that @alice:example.org receives all presence updates from @bob:example.com and +@charlie:somewhere.org, regardless of whether Alice shares a room with any of them.

+
from typing import Dict, Iterable, Set, Union
+
+from synapse.module_api import ModuleApi
+
+
+class CustomPresenceRouter:
+    def __init__(self, config: dict, api: ModuleApi):
+        self.api = api
+
+        self.api.register_presence_router_callbacks(
+            get_users_for_states=self.get_users_for_states,
+            get_interested_users=self.get_interested_users,
+        )
+
+    async def get_users_for_states(
+        self,
+        state_updates: Iterable["synapse.api.UserPresenceState"],
+    ) -> Dict[str, Set["synapse.api.UserPresenceState"]]:
+        res = {}
+        for update in state_updates:
+            if (
+                update.user_id == "@bob:example.com"
+                or update.user_id == "@charlie:somewhere.org"
+            ):
+                res.setdefault("@alice:example.com", set()).add(update)
+
+        return res
+
+    async def get_interested_users(
+        self,
+        user_id: str,
+    ) -> Union[Set[str], "synapse.module_api.PRESENCE_ALL_USERS"]:
+        if user_id == "@alice:example.com":
+            return {"@bob:example.com", "@charlie:somewhere.org"}
+
+        return set()
+
+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/v1.50/modules/spam_checker_callbacks.html b/v1.50/modules/spam_checker_callbacks.html new file mode 100644 index 0000000000..e6e82535a6 --- /dev/null +++ b/v1.50/modules/spam_checker_callbacks.html @@ -0,0 +1,463 @@ + + + + + + Spam checker callbacks - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Spam checker callbacks

+

Spam checker callbacks allow module developers to implement spam mitigation actions for +Synapse instances. Spam checker callbacks can be registered using the module API's +register_spam_checker_callbacks method.

+

Callbacks

+

The available spam checker callbacks are:

+

check_event_for_spam

+

First introduced in Synapse v1.37.0

+
async def check_event_for_spam(event: "synapse.events.EventBase") -> Union[bool, str]
+
+

Called when receiving an event from a client or via federation. The module can return +either a bool to indicate whether the event must be rejected because of spam, or a str +to indicate the event must be rejected because of spam and to give a rejection reason to +forward to clients.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns False, Synapse falls through to the next one. The value of the first +callback that does not return False will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

user_may_join_room

+

First introduced in Synapse v1.37.0

+
async def user_may_join_room(user: str, room: str, is_invited: bool) -> bool
+
+

Called when a user is trying to join a room. The module must return a bool to indicate +whether the user can join the room. The user is represented by their Matrix user ID (e.g. +@alice:example.com) and the room is represented by its Matrix ID (e.g. +!room:example.com). The module is also given a boolean to indicate whether the user +currently has a pending invite in the room.

+

This callback isn't called if the join is performed by a server administrator, or in the +context of a room creation.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

user_may_invite

+

First introduced in Synapse v1.37.0

+
async def user_may_invite(inviter: str, invitee: str, room_id: str) -> bool
+
+

Called when processing an invitation. The module must return a bool indicating whether +the inviter can invite the invitee to the given room. Both inviter and invitee are +represented by their Matrix user ID (e.g. @alice:example.com).

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

user_may_send_3pid_invite

+

First introduced in Synapse v1.45.0

+
async def user_may_send_3pid_invite(
+    inviter: str,
+    medium: str,
+    address: str,
+    room_id: str,
+) -> bool
+
+

Called when processing an invitation using a third-party identifier (also called a 3PID, +e.g. an email address or a phone number). The module must return a bool indicating +whether the inviter can invite the invitee to the given room.

+

The inviter is represented by their Matrix user ID (e.g. @alice:example.com), and the +invitee is represented by its medium (e.g. "email") and its address +(e.g. alice@example.com). See the Matrix specification +for more information regarding third-party identifiers.

+

For example, a call to this callback to send an invitation to the email address +alice@example.com would look like this:

+
await user_may_send_3pid_invite(
+    "@bob:example.com",  # The inviter's user ID
+    "email",  # The medium of the 3PID to invite
+    "alice@example.com",  # The address of the 3PID to invite
+    "!some_room:example.com",  # The ID of the room to send the invite into
+)
+
+

Note: If the third-party identifier is already associated with a matrix user ID, +user_may_invite will be used instead.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

user_may_create_room

+

First introduced in Synapse v1.37.0

+
async def user_may_create_room(user: str) -> bool
+
+

Called when processing a room creation request. The module must return a bool indicating +whether the given user (represented by their Matrix user ID) is allowed to create a room.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

user_may_create_room_alias

+

First introduced in Synapse v1.37.0

+
async def user_may_create_room_alias(user: str, room_alias: "synapse.types.RoomAlias") -> bool
+
+

Called when trying to associate an alias with an existing room. The module must return a +bool indicating whether the given user (represented by their Matrix user ID) is allowed +to set the given alias.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

user_may_publish_room

+

First introduced in Synapse v1.37.0

+
async def user_may_publish_room(user: str, room_id: str) -> bool
+
+

Called when trying to publish a room to the homeserver's public rooms directory. The +module must return a bool indicating whether the given user (represented by their +Matrix user ID) is allowed to publish the given room.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

check_username_for_spam

+

First introduced in Synapse v1.37.0

+
async def check_username_for_spam(user_profile: Dict[str, str]) -> bool
+
+

Called when computing search results in the user directory. The module must return a +bool indicating whether the given user profile can appear in search results. The profile +is represented as a dictionary with the following keys:

+
    +
  • user_id: The Matrix ID for this user.
  • +
  • display_name: The user's display name.
  • +
  • avatar_url: The mxc:// URL to the user's avatar.
  • +
+

The module is given a copy of the original dictionary, so modifying it from within the +module cannot modify a user's profile when included in user directory search results.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns False, Synapse falls through to the next one. The value of the first +callback that does not return False will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

check_registration_for_spam

+

First introduced in Synapse v1.37.0

+
async def check_registration_for_spam(
+    email_threepid: Optional[dict],
+    username: Optional[str],
+    request_info: Collection[Tuple[str, str]],
+    auth_provider_id: Optional[str] = None,
+) -> "synapse.spam_checker_api.RegistrationBehaviour"
+
+

Called when registering a new user. The module must return a RegistrationBehaviour +indicating whether the registration can go through or must be denied, or whether the user +may be allowed to register but will be shadow banned.

+

The arguments passed to this callback are:

+
    +
  • email_threepid: The email address used for registering, if any.
  • +
  • username: The username the user would like to register. Can be None, meaning that +Synapse will generate one later.
  • +
  • request_info: A collection of tuples, which first item is a user agent, and which +second item is an IP address. These user agents and IP addresses are the ones that were +used during the registration process.
  • +
  • auth_provider_id: The identifier of the SSO authentication provider, if any.
  • +
+

If multiple modules implement this callback, they will be considered in order. If a +callback returns RegistrationBehaviour.ALLOW, Synapse falls through to the next one. +The value of the first callback that does not return RegistrationBehaviour.ALLOW will +be used. If this happens, Synapse will not call any of the subsequent implementations of +this callback.

+

check_media_file_for_spam

+

First introduced in Synapse v1.37.0

+
async def check_media_file_for_spam(
+    file_wrapper: "synapse.rest.media.v1.media_storage.ReadableFileWrapper",
+    file_info: "synapse.rest.media.v1._base.FileInfo",
+) -> bool
+
+

Called when storing a local or remote file. The module must return a boolean indicating +whether the given file can be stored in the homeserver's media store.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns False, Synapse falls through to the next one. The value of the first +callback that does not return False will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

Example

+

The example below is a module that implements the spam checker callback +check_event_for_spam to deny any message sent by users whose Matrix user IDs are +mentioned in a configured list, and registers a web resource to the path +/_synapse/client/list_spam_checker/is_evil that returns a JSON object indicating +whether the provided user appears in that list.

+
import json
+from typing import Union
+
+from twisted.web.resource import Resource
+from twisted.web.server import Request
+
+from synapse.module_api import ModuleApi
+
+
+class IsUserEvilResource(Resource):
+    def __init__(self, config):
+        super(IsUserEvilResource, self).__init__()
+        self.evil_users = config.get("evil_users") or []
+
+    def render_GET(self, request: Request):
+        user = request.args.get(b"user")[0].decode()
+        request.setHeader(b"Content-Type", b"application/json")
+        return json.dumps({"evil": user in self.evil_users}).encode()
+
+
+class ListSpamChecker:
+    def __init__(self, config: dict, api: ModuleApi):
+        self.api = api
+        self.evil_users = config.get("evil_users") or []
+
+        self.api.register_spam_checker_callbacks(
+            check_event_for_spam=self.check_event_for_spam,
+        )
+
+        self.api.register_web_resource(
+            path="/_synapse/client/list_spam_checker/is_evil",
+            resource=IsUserEvilResource(config),
+        )
+
+    async def check_event_for_spam(self, event: "synapse.events.EventBase") -> Union[bool, str]:
+        return event.sender not in self.evil_users
+
+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/v1.50/modules/third_party_rules_callbacks.html b/v1.50/modules/third_party_rules_callbacks.html new file mode 100644 index 0000000000..addcb6e6cf --- /dev/null +++ b/v1.50/modules/third_party_rules_callbacks.html @@ -0,0 +1,393 @@ + + + + + + Third-party rules callbacks - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Third party rules callbacks

+

Third party rules callbacks allow module developers to add extra checks to verify the +validity of incoming events. Third party event rules callbacks can be registered using +the module API's register_third_party_rules_callbacks method.

+

Callbacks

+

The available third party rules callbacks are:

+

check_event_allowed

+

First introduced in Synapse v1.39.0

+
async def check_event_allowed(
+    event: "synapse.events.EventBase",
+    state_events: "synapse.types.StateMap",
+) -> Tuple[bool, Optional[dict]]
+
+

+This callback is very experimental and can and will break without notice. Module developers +are encouraged to implement check_event_for_spam from the spam checker category instead. +

+

Called when processing any incoming event, with the event and a StateMap +representing the current state of the room the event is being sent into. A StateMap is +a dictionary that maps tuples containing an event type and a state key to the +corresponding state event. For example retrieving the room's m.room.create event from +the state_events argument would look like this: state_events.get(("m.room.create", "")). +The module must return a boolean indicating whether the event can be allowed.

+

Note that this callback function processes incoming events coming via federation +traffic (on top of client traffic). This means denying an event might cause the local +copy of the room's history to diverge from that of remote servers. This may cause +federation issues in the room. It is strongly recommended to only deny events using this +callback function if the sender is a local user, or in a private federation in which all +servers are using the same module, with the same configuration.

+

If the boolean returned by the module is True, it may also tell Synapse to replace the +event with new data by returning the new event's data as a dictionary. In order to do +that, it is recommended the module calls event.get_dict() to get the current event as a +dictionary, and modify the returned dictionary accordingly.

+

If check_event_allowed raises an exception, the module is assumed to have failed. +The event will not be accepted but is not treated as explicitly rejected, either. +An HTTP request causing the module check will likely result in a 500 Internal +Server Error.

+

When the boolean returned by the module is False, the event is rejected. +(Module developers should not use exceptions for rejection.)

+

Note that replacing the event only works for events sent by local users, not for events +received over federation.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

on_create_room

+

First introduced in Synapse v1.39.0

+
async def on_create_room(
+    requester: "synapse.types.Requester",
+    request_content: dict,
+    is_requester_admin: bool,
+) -> None
+
+

Called when processing a room creation request, with the Requester object for the user +performing the request, a dictionary representing the room creation request's JSON body +(see the spec +for a list of possible parameters), and a boolean indicating whether the user performing +the request is a server admin.

+

Modules can modify the request_content (by e.g. adding events to its initial_state), +or deny the room's creation by raising a module_api.errors.SynapseError.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns without raising an exception, Synapse falls through to the next one. The +room creation will be forbidden as soon as one of the callbacks raises an exception. If +this happens, Synapse will not call any of the subsequent implementations of this +callback.

+

check_threepid_can_be_invited

+

First introduced in Synapse v1.39.0

+
async def check_threepid_can_be_invited(
+    medium: str,
+    address: str,
+    state_events: "synapse.types.StateMap",
+) -> bool:
+
+

Called when processing an invite via a third-party identifier (i.e. email or phone number). +The module must return a boolean indicating whether the invite can go through.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

check_visibility_can_be_modified

+

First introduced in Synapse v1.39.0

+
async def check_visibility_can_be_modified(
+    room_id: str,
+    state_events: "synapse.types.StateMap",
+    new_visibility: str,
+) -> bool:
+
+

Called when changing the visibility of a room in the local public room directory. The +visibility is a string that's either "public" or "private". The module must return a +boolean indicating whether the change can go through.

+

If multiple modules implement this callback, they will be considered in order. If a +callback returns True, Synapse falls through to the next one. The value of the first +callback that does not return True will be used. If this happens, Synapse will not call +any of the subsequent implementations of this callback.

+

on_new_event

+

First introduced in Synapse v1.47.0

+
async def on_new_event(
+    event: "synapse.events.EventBase",
+    state_events: "synapse.types.StateMap",
+) -> None:
+
+

Called after sending an event into a room. The module is passed the event, as well +as the state of the room after the event. This means that if the event is a state event, +it will be included in this state.

+

Note that this callback is called when the event has already been processed and stored +into the room, which means this callback cannot be used to deny persisting the event. To +deny an incoming event, see check_event_for_spam instead.

+

If multiple modules implement this callback, Synapse runs them all in order.

+

Example

+

The example below is a module that implements the third-party rules callback +check_event_allowed to censor incoming messages as dictated by a third-party service.

+
from typing import Optional, Tuple
+
+from synapse.module_api import ModuleApi
+
+_DEFAULT_CENSOR_ENDPOINT = "https://my-internal-service.local/censor-event"
+
+class EventCensorer:
+    def __init__(self, config: dict, api: ModuleApi):
+        self.api = api
+        self._endpoint = config.get("endpoint", _DEFAULT_CENSOR_ENDPOINT)
+
+        self.api.register_third_party_rules_callbacks(
+            check_event_allowed=self.check_event_allowed,
+        )
+
+    async def check_event_allowed(
+        self,
+        event: "synapse.events.EventBase",
+        state_events: "synapse.types.StateMap",
+    ) -> Tuple[bool, Optional[dict]]:
+        event_dict = event.get_dict()
+        new_event_content = await self.api.http_client.post_json_get_json(
+            uri=self._endpoint, post_json=event_dict,
+        )
+        event_dict["content"] = new_event_content
+        return event_dict
+
+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/v1.50/modules/writing_a_module.html b/v1.50/modules/writing_a_module.html new file mode 100644 index 0000000000..2bec77d356 --- /dev/null +++ b/v1.50/modules/writing_a_module.html @@ -0,0 +1,316 @@ + + + + + + Writing a module - Synapse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+ +
+ +
+ +

Writing a module

+

A module is a Python class that uses Synapse's module API to interact with the +homeserver. It can register callbacks that Synapse will call on specific operations, as +well as web resources to attach to Synapse's web server.

+

When instantiated, a module is given its parsed configuration as well as an instance of +the synapse.module_api.ModuleApi class. The configuration is a dictionary, and is +either the output of the module's parse_config static method (see below), or the +configuration associated with the module in Synapse's configuration file.

+

See the documentation for the ModuleApi class +here.

+

When Synapse runs with several modules configured

+

If Synapse is running with other modules configured, the order each module appears in +within the modules section of the Synapse configuration file might restrict what it can +or cannot register. See this section for more +information.

+

On top of the rules listed in the link above, if a callback returns a value that should +cause the current operation to fail (e.g. if a callback checking an event returns with a +value that should cause the event to be denied), Synapse will fail the operation and +ignore any subsequent callbacks that should have been run after this one.

+

The documentation for each callback mentions how Synapse behaves when +multiple modules implement it.

+

Handling the module's configuration

+

A module can implement the following static method:

+
@staticmethod
+def parse_config(config: dict) -> dict
+
+

This method is given a dictionary resulting from parsing the YAML configuration for the +module. It may modify it (for example by parsing durations expressed as strings (e.g. +"5d") into milliseconds, etc.), and return the modified dictionary. It may also verify +that the configuration is correct, and raise an instance of +synapse.module_api.errors.ConfigError if not.

+

Registering a web resource

+

Modules can register web resources onto Synapse's web server using the following module +API method:

+
def ModuleApi.register_web_resource(path: str, resource: IResource) -> None
+
+

The path is the full absolute path to register the resource at. For example, if you +register a resource for the path /_synapse/client/my_super_module/say_hello, Synapse +will serve it at http(s)://[HS_URL]/_synapse/client/my_super_module/say_hello. Note +that Synapse does not allow registering resources for several sub-paths in the /_matrix +namespace (such as anything under /_matrix/client for example). It is strongly +recommended that modules register their web resources under the /_synapse/client +namespace.

+

The provided resource is a Python class that implements Twisted's IResource +interface (such as Resource).

+

Only one resource can be registered for a given path. If several modules attempt to +register a resource for the same path, the module that appears first in Synapse's +configuration file takes priority.

+

Modules must register their web resources in their __init__ method.

+

Registering a callback

+

Modules can use Synapse's module API to register callbacks. Callbacks are functions that +Synapse will call when performing specific actions. Callbacks must be asynchronous (unless +specified otherwise), and are split in categories. A single module may implement callbacks +from multiple categories, and is under no obligation to implement all callbacks from the +categories it registers callbacks for.

+

Modules can register callbacks using one of the module API's register_[...]_callbacks +methods. The callback functions are passed to these methods as keyword arguments, with +the callback name as the argument name and the function as its value. A +register_[...]_callbacks method exists for each category.

+

Callbacks for each category can be found on their respective page of the +Synapse documentation website.

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file -- cgit 1.5.1