|
| 1 | +# |
| 2 | +# This file is licensed under the Affero General Public License (AGPL) version 3. |
| 3 | +# |
| 4 | +# Copyright 2021 The Matrix.org Foundation C.I.C |
| 5 | +# Copyright (C) 2024 New Vector, Ltd |
| 6 | +# |
| 7 | +# This program is free software: you can redistribute it and/or modify |
| 8 | +# it under the terms of the GNU Affero General Public License as |
| 9 | +# published by the Free Software Foundation, either version 3 of the |
| 10 | +# License, or (at your option) any later version. |
| 11 | +# |
| 12 | +# See the GNU Affero General Public License for more details: |
| 13 | +# <https://www.gnu.org/licenses/agpl-3.0.html>. |
| 14 | +# |
| 15 | +# Originally licensed under the Apache License, Version 2.0: |
| 16 | +# <http://www.apache.org/licenses/LICENSE-2.0>. |
| 17 | +# |
| 18 | +# [This file includes modifications made by New Vector Limited] |
| 19 | +# |
| 20 | +# |
| 21 | +import logging |
| 22 | +from http import HTTPStatus |
| 23 | +from typing import Any, Dict, Tuple |
| 24 | + |
| 25 | +from synapse.api.constants import AccountDataTypes, EventTypes, Membership |
| 26 | +from synapse.api.errors import SynapseError |
| 27 | +from synapse.config.auto_accept_invites import AutoAcceptInvitesConfig |
| 28 | +from synapse.module_api import EventBase, ModuleApi, run_as_background_process |
| 29 | + |
| 30 | +logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | + |
| 33 | +class InviteAutoAccepter: |
| 34 | + def __init__(self, config: AutoAcceptInvitesConfig, api: ModuleApi): |
| 35 | + # Keep a reference to the Module API. |
| 36 | + self._api = api |
| 37 | + self._config = config |
| 38 | + |
| 39 | + if not self._config.enabled: |
| 40 | + return |
| 41 | + |
| 42 | + should_run_on_this_worker = config.worker_to_run_on == self._api.worker_name |
| 43 | + |
| 44 | + if not should_run_on_this_worker: |
| 45 | + logger.info( |
| 46 | + "Not accepting invites on this worker (configured: %r, here: %r)", |
| 47 | + config.worker_to_run_on, |
| 48 | + self._api.worker_name, |
| 49 | + ) |
| 50 | + return |
| 51 | + |
| 52 | + logger.info( |
| 53 | + "Accepting invites on this worker (here: %r)", self._api.worker_name |
| 54 | + ) |
| 55 | + |
| 56 | + # Register the callback. |
| 57 | + self._api.register_third_party_rules_callbacks( |
| 58 | + on_new_event=self.on_new_event, |
| 59 | + ) |
| 60 | + |
| 61 | + async def on_new_event(self, event: EventBase, *args: Any) -> None: |
| 62 | + """Listens for new events, and if the event is an invite for a local user then |
| 63 | + automatically accepts it. |
| 64 | +
|
| 65 | + Args: |
| 66 | + event: The incoming event. |
| 67 | + """ |
| 68 | + # Check if the event is an invite for a local user. |
| 69 | + is_invite_for_local_user = ( |
| 70 | + event.type == EventTypes.Member |
| 71 | + and event.is_state() |
| 72 | + and event.membership == Membership.INVITE |
| 73 | + and self._api.is_mine(event.state_key) |
| 74 | + ) |
| 75 | + |
| 76 | + # Only accept invites for direct messages if the configuration mandates it. |
| 77 | + is_direct_message = event.content.get("is_direct", False) |
| 78 | + is_allowed_by_direct_message_rules = ( |
| 79 | + not self._config.accept_invites_only_for_direct_messages |
| 80 | + or is_direct_message is True |
| 81 | + ) |
| 82 | + |
| 83 | + # Only accept invites from remote users if the configuration mandates it. |
| 84 | + is_from_local_user = self._api.is_mine(event.sender) |
| 85 | + is_allowed_by_local_user_rules = ( |
| 86 | + not self._config.accept_invites_only_from_local_users |
| 87 | + or is_from_local_user is True |
| 88 | + ) |
| 89 | + |
| 90 | + if ( |
| 91 | + is_invite_for_local_user |
| 92 | + and is_allowed_by_direct_message_rules |
| 93 | + and is_allowed_by_local_user_rules |
| 94 | + ): |
| 95 | + # Make the user join the room. We run this as a background process to circumvent a race condition |
| 96 | + # that occurs when responding to invites over federation (see https://github.com/matrix-org/synapse-auto-accept-invite/issues/12) |
| 97 | + run_as_background_process( |
| 98 | + "retry_make_join", |
| 99 | + self._retry_make_join, |
| 100 | + event.state_key, |
| 101 | + event.state_key, |
| 102 | + event.room_id, |
| 103 | + "join", |
| 104 | + bg_start_span=False, |
| 105 | + ) |
| 106 | + |
| 107 | + if is_direct_message: |
| 108 | + # Mark this room as a direct message! |
| 109 | + await self._mark_room_as_direct_message( |
| 110 | + event.state_key, event.sender, event.room_id |
| 111 | + ) |
| 112 | + |
| 113 | + async def _mark_room_as_direct_message( |
| 114 | + self, user_id: str, dm_user_id: str, room_id: str |
| 115 | + ) -> None: |
| 116 | + """ |
| 117 | + Marks a room (`room_id`) as a direct message with the counterparty `dm_user_id` |
| 118 | + from the perspective of the user `user_id`. |
| 119 | +
|
| 120 | + Args: |
| 121 | + user_id: the user for whom the membership is changing |
| 122 | + dm_user_id: the user performing the membership change |
| 123 | + room_id: room id of the room the user is invited to |
| 124 | + """ |
| 125 | + |
| 126 | + # This is a dict of User IDs to tuples of Room IDs |
| 127 | + # (get_global will return a frozendict of tuples as it freezes the data, |
| 128 | + # but we should accept either frozen or unfrozen variants.) |
| 129 | + # Be careful: we convert the outer frozendict into a dict here, |
| 130 | + # but the contents of the dict are still frozen (tuples in lieu of lists, |
| 131 | + # etc.) |
| 132 | + dm_map: Dict[str, Tuple[str, ...]] = dict( |
| 133 | + await self._api.account_data_manager.get_global( |
| 134 | + user_id, AccountDataTypes.DIRECT |
| 135 | + ) |
| 136 | + or {} |
| 137 | + ) |
| 138 | + |
| 139 | + if dm_user_id not in dm_map: |
| 140 | + dm_map[dm_user_id] = (room_id,) |
| 141 | + else: |
| 142 | + dm_rooms_for_user = dm_map[dm_user_id] |
| 143 | + assert isinstance(dm_rooms_for_user, (tuple, list)) |
| 144 | + |
| 145 | + dm_map[dm_user_id] = tuple(dm_rooms_for_user) + (room_id,) |
| 146 | + |
| 147 | + await self._api.account_data_manager.put_global( |
| 148 | + user_id, AccountDataTypes.DIRECT, dm_map |
| 149 | + ) |
| 150 | + |
| 151 | + async def _retry_make_join( |
| 152 | + self, sender: str, target: str, room_id: str, new_membership: str |
| 153 | + ) -> None: |
| 154 | + """ |
| 155 | + A function to retry sending the `make_join` request with an increasing backoff. This is |
| 156 | + implemented to work around a race condition when receiving invites over federation. |
| 157 | +
|
| 158 | + Args: |
| 159 | + sender: the user performing the membership change |
| 160 | + target: the user for whom the membership is changing |
| 161 | + room_id: room id of the room to join to |
| 162 | + new_membership: the type of membership event (in this case will be "join") |
| 163 | + """ |
| 164 | + |
| 165 | + sleep = 0 |
| 166 | + retries = 0 |
| 167 | + join_event = None |
| 168 | + |
| 169 | + while retries < 5: |
| 170 | + try: |
| 171 | + await self._api.sleep(sleep) |
| 172 | + join_event = await self._api.update_room_membership( |
| 173 | + sender=sender, |
| 174 | + target=target, |
| 175 | + room_id=room_id, |
| 176 | + new_membership=new_membership, |
| 177 | + ) |
| 178 | + except SynapseError as e: |
| 179 | + if e.code == HTTPStatus.FORBIDDEN: |
| 180 | + logger.debug( |
| 181 | + f"Update_room_membership was forbidden. This can sometimes be expected for remote invites. Exception: {e}" |
| 182 | + ) |
| 183 | + else: |
| 184 | + logger.warn( |
| 185 | + f"Update_room_membership raised the following unexpected (SynapseError) exception: {e}" |
| 186 | + ) |
| 187 | + except Exception as e: |
| 188 | + logger.warn( |
| 189 | + f"Update_room_membership raised the following unexpected exception: {e}" |
| 190 | + ) |
| 191 | + |
| 192 | + sleep = 2**retries |
| 193 | + retries += 1 |
| 194 | + |
| 195 | + if join_event is not None: |
| 196 | + break |
0 commit comments