Repository navigation
Add an endpoint to invite guests to a room by email #304
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
447e570
Add an endpoint to invite guests to a room by email
devonh 9931411
Put the invite endpoint behind an `email_invites` config block
devonh e934ba3
Check the inviter's power level with Synapse's own rules
devonh 72a92c8
Refuse guest invites from guests and outside knock rooms
devonh d6f25fb
Limit how many guest invites an inviter sends
devonh 4aeac1d
Send the room name and the inviter with guest invites
devonh 2218c40
Map MAS errors from guest invites
devonh 2370ccc
Document email invites
devonh ac66068
Cleanup README
devonh d9be685
Use Synapse's constants for event types and content fields in guest i…
devonh adba40c
Allow guest invites to knock_restricted rooms
devonh 261a21e
Let MAS assign invited guests' localparts
devonh 631a214
Call MAS's `room-invites` endpoint
devonh c87ced9
Drop a link to the removed deployment checklist
devonh fb55fc0
Mint guest invite codes and send their emails in separate MAS calls
devonh e7f9996
Send MAS a minijinja username template
devonh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
226 changes: 226 additions & 0 deletions
226
modules/restricted-guests/synapse/synapse_guest_module/guest_invite_servlet.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,226 @@ | ||
| # Copyright 2026 Element Creations Ltd. | ||
| # | ||
| # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial | ||
| # Please see LICENSE files in the project root for full details. | ||
|
|
||
| import json | ||
| import logging | ||
| from datetime import datetime, timezone | ||
| from typing import Any, Callable, Dict, Optional, Tuple | ||
|
|
||
| from synapse.api.constants import EventContentFields, EventTypes, JoinRules, Membership | ||
| from synapse.api.errors import HttpResponseException | ||
| from synapse.api.ratelimiting import Ratelimiter | ||
| from synapse.config.ratelimiting import RatelimitSettings | ||
| from synapse.event_auth import get_named_level, get_user_power_level | ||
| from synapse.http.site import SynapseRequest | ||
| from synapse.module_api import ( | ||
| DirectServeJsonResource, | ||
| EventBase, | ||
| ModuleApi, | ||
| StateMap, | ||
| parse_json_object_from_request, | ||
| ) | ||
|
|
||
| from synapse_guest_module.config import GuestModuleConfig | ||
| from synapse_guest_module.mas_admin_client import MasAdminClient | ||
|
|
||
| logger = logging.getLogger("synapse.contrib." + __name__) | ||
|
|
||
|
|
||
| class GuestInviteServlet(DirectServeJsonResource): | ||
| """The `POST /_synapse/client/invite_guests` endpoint invites a list of email | ||
| addresses to a room as guests. It requires the `room_id` and `emails` | ||
| properties. | ||
|
|
||
| Each address is emailed a link to register as a guest, which MAS mints an | ||
| invite code for and sends out. Nothing exists on this homeserver until a | ||
| recipient follows their link, and MAS assigns the guest's localpart then. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| config: GuestModuleConfig, | ||
| api: ModuleApi, | ||
| mas_admin_client: MasAdminClient, | ||
| is_module_guest: Callable[[str], bool], | ||
| ): | ||
| super().__init__() | ||
| self._api = api | ||
| self._config = config | ||
| self._mas_admin_client = mas_admin_client | ||
| self._is_module_guest = is_module_guest | ||
|
|
||
| # Per worker, and reset on restart | ||
| per_hour = config.email_invites.per_inviter_per_hour | ||
| self._ratelimiter = Ratelimiter( | ||
| store=api._hs.get_datastores().main, | ||
| clock=api._hs.get_clock(), | ||
| cfg=RatelimitSettings( | ||
| key="guest_module_invite_guests", | ||
| per_second=per_hour / 3600, | ||
| burst_count=per_hour, | ||
| ), | ||
| ) | ||
|
|
||
| async def _async_render_POST( | ||
|
Check failure on line 66 in modules/restricted-guests/synapse/synapse_guest_module/guest_invite_servlet.py
|
||
| self, request: SynapseRequest | ||
| ) -> Tuple[int, Dict[str, Any]]: | ||
| """Have MAS mint an invite code per address and email out the links. | ||
| MAS assigns each guest's localpart from the username template. | ||
| """ | ||
|
|
||
| requester = await self._api.get_user_by_req(request) | ||
|
|
||
| json_dict = parse_json_object_from_request(request) | ||
|
|
||
| room_id = json_dict.get("room_id") | ||
| if not isinstance(room_id, str) or not room_id.startswith("!"): | ||
| return 400, {"msg": "You must provide a valid 'room_id'"} | ||
|
erikjohnston marked this conversation as resolved.
Resolved
|
||
|
|
||
| emails = json_dict.get("emails") | ||
| if ( | ||
| not isinstance(emails, list) | ||
| or len(emails) == 0 | ||
| or not all( | ||
| isinstance(email, str) and len(email.strip()) > 0 for email in emails | ||
| ) | ||
| ): | ||
| return 400, { | ||
| "msg": "You must provide 'emails' as a non-empty list of strings" | ||
| } | ||
|
|
||
| # Keyed ignoring case, keeping the first spelling of each address | ||
| unique_emails: Dict[str, str] = {} | ||
| for email in emails: | ||
| unique_emails.setdefault(email.strip().lower(), email.strip()) | ||
|
|
||
| max_emails = self._config.email_invites.max_emails | ||
| if len(unique_emails) > max_emails: | ||
| return 400, {"msg": f"You can invite at most {max_emails} emails at once"} | ||
|
|
||
| user_id = requester.user.to_string() | ||
| if self._is_module_guest(user_id): | ||
| return 403, {"msg": "Guests can't invite guests"} | ||
|
|
||
| state = await self._api.get_room_state( | ||
| room_id, | ||
| [ | ||
| (EventTypes.Create, ""), | ||
| (EventTypes.JoinRules, ""), | ||
| (EventTypes.Member, user_id), | ||
| (EventTypes.Name, ""), | ||
| (EventTypes.PowerLevels, ""), | ||
| ], | ||
| ) | ||
| if not self._may_invite(user_id, state): | ||
| return 403, {"msg": "You are not allowed to invite users to this room"} | ||
|
|
||
| # An email-invited guest has no Matrix invite, so it gets in by asking to join | ||
| join_rules = state.get((EventTypes.JoinRules, "")) | ||
| if join_rules is None or join_rules.content.get("join_rule") not in ( | ||
| JoinRules.KNOCK, | ||
| JoinRules.KNOCK_RESTRICTED, | ||
| ): | ||
| return 403, { | ||
| "msg": "Guests can only be invited to rooms they can ask to join", | ||
| "reason": "room_not_knockable", | ||
| } | ||
|
|
||
| if room_id in self._config.rooms_forbidden_to_guests: | ||
| return 403, {"msg": "Guests are forbidden from this room"} | ||
|
|
||
| # Last, so that a refused request doesn't spend the limit | ||
| await self._ratelimiter.ratelimit(requester, n_actions=len(unique_emails)) | ||
|
erikjohnston marked this conversation as resolved.
Resolved
|
||
|
|
||
| # A minijinja template, which MAS renders when the guest registers | ||
| username = self._config.user_id_prefix + "{{ random }}" | ||
| expires_at = datetime.fromtimestamp( | ||
| self._api._hs.get_clock().time() | ||
| + self._config.email_invites.invite_lifetime, | ||
| tz=timezone.utc, | ||
| ) | ||
|
|
||
| logger.info( | ||
| "'%s' is inviting %d guest(s) to '%s'", user_id, len(unique_emails), room_id | ||
| ) | ||
| room_name = _non_empty_string( | ||
| state.get((EventTypes.Name, "")), EventContentFields.ROOM_NAME | ||
| ) | ||
| inviter_name = _non_empty_string( | ||
| state.get((EventTypes.Member, user_id)), | ||
| EventContentFields.MEMBERSHIP_DISPLAYNAME, | ||
| ) | ||
| try: | ||
| # Outside the inner `try`, because a refused token request is between | ||
| # this module and MAS, not the inviter's to see | ||
| token = await self._mas_admin_client.request_admin_token() | ||
| try: | ||
| # Every address is minted for before any is sent, so a refused | ||
| # address sends no email at all | ||
| token_ids = [ | ||
| await self._mas_admin_client.create_registration_token( | ||
| email, username, room_id, expires_at, token | ||
| ) | ||
| for email in unique_emails.values() | ||
| ] | ||
| scheduled = await self._mas_admin_client.send_invite_emails( | ||
| token_ids, room_name, user_id, inviter_name, token | ||
| ) | ||
| except HttpResponseException as e: | ||
| if e.code == 400: | ||
| return 400, { | ||
| "msg": _first_error_title(e.response) | ||
| or "MAS refused the invites" | ||
| } | ||
| if e.code == 404: | ||
| logger.warning( | ||
| "MAS answered guest invites with 404: it's too old or isn't " | ||
| "at 'mas.admin_api_base_url'" | ||
| ) | ||
| raise | ||
| # A timeout is a `SynapseError`, and a connection failure a Twisted error | ||
| except Exception: | ||
| logger.exception("Failed to send guest invites to MAS") | ||
| return 502, {"msg": "Failed to send the invites"} | ||
|
|
||
| return 202, {"scheduled": scheduled} | ||
|
|
||
| @staticmethod | ||
| def _may_invite(user_id: str, state: StateMap[EventBase]) -> bool: | ||
| """Whether this user may invite guests to the room with this state. | ||
|
|
||
| The guests are invited by email rather than by a membership event, so | ||
| nothing else checks this. It mirrors what Synapse requires of a real | ||
| invite: the user is joined to the room and meets its invite power level. | ||
| """ | ||
| # A room this server isn't in has no state, not even the create event | ||
| # that `get_user_power_level` asserts | ||
| member = state.get((EventTypes.Member, user_id)) | ||
| if ( | ||
| member is None | ||
| or member.content.get(EventContentFields.MEMBERSHIP) != Membership.JOIN | ||
| ): | ||
| return False | ||
|
|
||
| return get_user_power_level(user_id, state) >= get_named_level( | ||
| state, "invite", 0 | ||
| ) | ||
|
|
||
|
|
||
| def _non_empty_string(event: Optional[EventBase], key: str) -> Optional[str]: | ||
| """The event's content value for this key, if it's a non-empty string. | ||
|
|
||
| Room members set these, so they can hold anything. | ||
| """ | ||
| value = event.content.get(key) if event is not None else None | ||
| return value if isinstance(value, str) and value else None | ||
|
|
||
|
|
||
| def _first_error_title(body: bytes) -> Optional[str]: | ||
| """The first title in a MAS admin API error body, `{"errors": [{"title"}]}`.""" | ||
| try: | ||
| title = json.loads(body)["errors"][0]["title"] | ||
| except (ValueError, LookupError, TypeError): | ||
| return None | ||
| return title if isinstance(title, str) else None | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These defaults seem okay 🤷
Basically just numbers to prevent users from generating email / endpoint spam.
Either way, they are configurable to meet a deployments actual usage.