Fix 500s on membership changes in rooms the server is not in (#20499)

[More internal context
here](https://claude.ai/artifact/2BcZgjUcvHJjV1jdsuPHLv#dbe58feb-2677),
this is part of a series of PRs to try and fix many buggy membership
transitions.

This PR fixes a 500 error when trying to update the membership in rooms
where the server has no forward extremities.

To understand what this concretely means, the easiest example to
understand is when you try to reject a remote invite *twice*. This
means:

- Your local homeserver got [an invite from a remote
server](https://spec.matrix.org/latest/server-server-api/#inviting-to-a-room)
for a room it doesn't know anything about.
- In this case, it is storing the invitation as an "out of band" event,
and doesn't have any forward extremities for this room
- The spec then gives us special
[`/make_join`](https://spec.matrix.org/latest/server-server-api/#joining-rooms)
and
[`/make_leave`](https://spec.matrix.org/latest/server-server-api/#leaving-rooms-rejecting-invites)
dances that will let our homeserver craft proper join or leave events
without yet being in the room
- That's what the [`/leave` C-S
API](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidleave)
uses, allowing a client to leave an invited room. Problem is when you
call this API twice:
- On the first `/leave`, our current local membership is "invite", so it
will do the `/make_leave` dance (or generate the leave itself if the
remote can't be reached), and then update our current local membership
to "leave" and store that leave event also out of band
- On the second `/leave`, our current local membership is "leave", so it
will try to build that event regularly, but is missing forward
extremities to do so

The reason clients call `/leave` twice is that they miss the leave event
in some circumstances, which will be addressed in other PRs.

But the "double leave" issue was always a problem. This *technically*
addresses https://github.com/element-hq/synapse/issues/18473 and
https://github.com/element-hq/synapse/issues/19485 by not making those
`/leave` return a 500, but the real problem is the leave event not going
down to clients.

This does two things, in two separate commits:

- first a safeguard: in a room we are not in and have no forward
extremities for, any membership change that isn't one of the special
cases gets a 403 because you're "not in the room" instead of a 500
- then replicate what we do normally which is to deduplicate the event
for identical `/leave` when the leave is stored OOB

#20503 is stacked on top of this PR because it makes a new case
reachable (a local user banned in a room we are not in), where `/leave`
would hit the same 500 without the safeguard here.

<details>
<summary>Original PR description from Claude Code 🤖</summary>

A user rejects a remote invite while the inviting server can't be
reached, or rescinds a knock. Synapse generates a local out-of-band
leave, stores it as an outlier and records it in
`local_current_membership`. If the user then calls `/leave` again
(clients do when they did not see the first leave; #20438 is one such
case), `update_membership_locked` finds no prev events for the room, the
LEAVE branch has no arm for a current membership of `leave`, and
`create_new_client_event` fails its "no prev_events" assertion with a
500. `/invite`, `/ban` and `/kick` in such a room hit the same
assertion. This is a few hundred 500s a day on matrix.org, mostly people
rejecting spam invites from servers that no longer answer. Reported as
#18473, #19485 and #18003.

When the server is not in the room and the room has no forward
extremities, an identical leave (same sender, same content) now returns
the existing event, as `deduplicate_state_event` does in a room the
server is in. Any other membership change there gets a 403
(`M_FORBIDDEN`, or `M_NOT_JOINED` with MSC3848) before an event is
built: a leave with different content, a leave by a banned user, and
`/invite`, `/ban` or `/kick`. That is the error the auth rules give a
sender who is not in the room. A room the server has left but still
holds forward extremities for keeps taking the existing path, which
already answers through the deduplication and the auth rules. Rooms
whose extremities `delete_old_current_state_events` removed are covered
too.

The leave is still not sent to the remote server, and it is still
invisible to clients; #20438 is for the latter.

Tests in `tests/handlers/test_room_member.py`: a repeat leave after a
failed invite rejection (the same event comes back, different content
gets a 403), and an invite, ban and kick in that room. All of them fail
with the assertion on develop.

#20503 is stacked on this. #20444 adds a `BAN` arm to the same branch
and will need a rebase.

https://claude.ai/code/session_01Usuxv8JofVGciXVtxbdTtr

</details>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Quentin GliechandClaude Fable 5.2 authored and GitHub committed 2026-11-17 15:57:17 +01:00
1 parent 40f63e0fb1
commit cf0b0a9239
3 files changed
+138 -1

No files matched your search

+1
View File
@@ -0,0 +1 @@
Fix `/leave`, `/invite`, `/ban` and `/kick` returning a 500 error in some rooms the server is not in, such as when leaving a room again after rejecting an invite or rescinding a knock that could not be sent over federation.
+27
View File
@@ -40,6 +40,7 @@ from synapse.api.errors import (
PartialStateConflictError,
ShadowBanError,
SynapseError,
UnstableSpecAuthError,
UnsupportedRoomVersionError,
)
from synapse.api.ratelimiting import Ratelimiter
@@ -1051,6 +1052,8 @@ class RoomMemberHandler(metaclass=abc.ABCMeta):
if action == "kick":
raise AuthError(403, "The target user is not in the room")
rejecting_local_invite = False
if effective_membership_state == Membership.JOIN:
if requester.is_guest:
guest_can_join = await self._can_guest_join(partial_state_before_join)
@@ -1181,6 +1184,7 @@ class RoomMemberHandler(metaclass=abc.ABCMeta):
# the inviter was on our server, but has now left. Carry on
# with the normal rejection codepath, which will also send the
# rejection out to any other servers we believe are still in the room.
rejecting_local_invite = True
# thanks to overzealous cleaning up of event_forward_extremities in
# `delete_old_current_state_events`, it's possible to end up with no
@@ -1200,6 +1204,19 @@ class RoomMemberHandler(metaclass=abc.ABCMeta):
knock.event_id, txn_id, requester, content
)
# An identical leave by the same sender returns the existing event,
# as `deduplicate_state_event` does in rooms we are in.
elif current_membership_type == Membership.LEAVE:
leave = await self.store.get_event(current_membership_event_id)
expected_content = {**content, "membership": Membership.LEAVE}
if (
leave.sender == requester.user.to_string()
and leave.content == expected_content
):
# we know it was persisted, so must have a stream ordering.
assert leave.internal_metadata.stream_ordering
return leave.event_id, leave.internal_metadata.stream_ordering
elif effective_membership_state == Membership.KNOCK:
if not is_host_in_room:
# we used to add the domain of the room ID to remote_room_hosts.
@@ -1223,6 +1240,16 @@ class RoomMemberHandler(metaclass=abc.ABCMeta):
requester, remote_room_hosts, room_id, target, content
)
# We can only build an event in a room we are in, or on top of an invite
# sent by one of our users. Refuse as the auth rules refuse a sender who is
# not in the room.
if not is_host_in_room and not rejecting_local_invite:
raise UnstableSpecAuthError(
403,
"%s not in room %s." % (requester.user, room_id),
errcode=Codes.NOT_JOINED,
)
return await self._local_membership_update(
requester=requester,
target=target,
+110 -1
View File
@@ -1,12 +1,15 @@
from unittest.mock import AsyncMock, patch
from parameterized import parameterized
from twisted.internet.testing import MemoryReactor
import synapse.rest.admin
import synapse.rest.client.login
import synapse.rest.client.room
from synapse.api.constants import AccountDataTypes, EventTypes, Membership
from synapse.api.errors import Codes, LimitExceededError, SynapseError
from synapse.api.errors import AuthError, Codes, LimitExceededError, SynapseError
from synapse.api.room_versions import RoomVersions
from synapse.crypto.event_signing import add_hashes_and_signatures
from synapse.federation.federation_client import SendJoinResult
from synapse.server import HomeServer
@@ -446,6 +449,112 @@ class RoomMemberMasterHandlerTestCase(HomeserverTestCase):
self.assertEqual(initial_count, new_count)
def _reject_invite_from_unreachable_server(self) -> tuple[str, str]:
"""
Has bob reject an invite to a room our server is not in, sent by a server
that cannot be reached.
Returns:
The room ID and the event ID of bob's leave.
"""
remote_server = "other.invalid"
room_id = f"!room:{remote_server}"
# The remote server invites bob. Our server stores the invite as an
# outlier: it has no other event of the room.
invite = make_test_pdu_event(
{
"type": EventTypes.Member,
"content": {"membership": Membership.INVITE},
"room_id": room_id,
"sender": f"@inviter:{remote_server}",
"state_key": self.bob,
},
# Room IDs of later room versions are the hash of a create event, which
# this test does not build.
RoomVersions.V11,
)
self.get_success(
self.hs.get_federation_handler().on_invite_request(
origin=remote_server, event=invite, room_version=invite.room_version
)
)
# Bob rejects the invite. The `make_leave` request to the remote server
# fails, so our server builds the leave itself, as another outlier.
with patch.object(
self.hs.get_federation_client(),
"make_membership_event",
AsyncMock(side_effect=SynapseError(502, "Failed to make_leave")),
):
leave_event_id, _ = self.get_success(
self.handler.update_membership(
requester=create_requester(self.bob),
target=self.bob_ID,
room_id=room_id,
action=Membership.LEAVE,
)
)
return room_id, leave_event_id
def test_repeat_leave_after_out_of_band_leave(self) -> None:
"""
Leaving a room again after an out-of-band leave returns the existing leave,
and a leave with a different reason is forbidden.
"""
# Bob's leave is an outlier in a room our server is not in, so there is no
# event to build a second leave on.
room_id, leave_event_id = self._reject_invite_from_unreachable_server()
# Clients repeat the request when they did not see the first leave. The
# same leave again returns the event we already have.
event_id, _ = self.get_success(
self.handler.update_membership(
requester=create_requester(self.bob),
target=self.bob_ID,
room_id=room_id,
action=Membership.LEAVE,
)
)
self.assertEqual(event_id, leave_event_id)
# A different leave would be a new event. It is refused, as the auth rules
# refuse a leave from a user who has already left.
failure = self.get_failure(
self.handler.update_membership(
requester=create_requester(self.bob),
target=self.bob_ID,
room_id=room_id,
action=Membership.LEAVE,
content={"reason": "changed my mind"},
),
AuthError,
)
self.assertEqual(failure.value.code, 403)
@parameterized.expand([(Membership.INVITE,), (Membership.BAN,), ("kick",)])
def test_membership_change_after_out_of_band_leave(self, action: str) -> None:
"""
A local user cannot invite, ban or kick in a room our server is not in and
has no forward extremities of.
"""
# The only events our server has of the room are bob's invite and leave,
# both outliers.
room_id, _ = self._reject_invite_from_unreachable_server()
# Alice is not in the room either, so the request is refused. There is no
# event to build her invite, ban or kick on.
failure = self.get_failure(
self.handler.update_membership(
requester=create_requester(self.alice),
target=self.bob_ID,
room_id=room_id,
action=action,
),
AuthError,
)
self.assertEqual(failure.value.code, 403)
class TestMSC4155InviteFiltering(FederatingHomeserverTestCase):
"""Tests for MSC4155-style invite filtering."""