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

Experimental support for MSC3266 Room Summary API #10394

Merged
merged 41 commits into from
Aug 16, 2021
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
7d9c34d
Extract ResolveRoomIdMixin and reuse it for /_matrix/client/r0/join/{…
t3chguy Jul 14, 2021
ef295d1
First cut of a local-only poc for MSC3266
t3chguy Jul 14, 2021
85abffc
Update allowed_spaces to allowed_room_ids to match Space Summary API
t3chguy Jul 15, 2021
b0c8e02
Extract _is_room_accessible into synapse.api.auth.Auth
t3chguy Jul 15, 2021
d169cd8
Extract build_room_entry into a mixin, updates Space Summary API allo…
t3chguy Jul 15, 2021
01b222a
remove unused variables
t3chguy Jul 15, 2021
9227efc
delint
t3chguy Jul 15, 2021
c02485c
fix types
t3chguy Jul 15, 2021
0fa04fe
Fix typo in the msc3266 experimental config flag
t3chguy Jul 15, 2021
3982736
Merge branch 'develop' into msc3266
t3chguy Jul 19, 2021
957cb4f
Merge branch 'develop' of https://github.com/matrix-org/synapse into …
t3chguy Aug 4, 2021
9994f12
extract requester_can_see_room_entry to reuse in both space and room …
t3chguy Aug 5, 2021
b2c8a7c
Add newsfragment
t3chguy Aug 5, 2021
e6e7ecf
Add tests for the room_summary handler and make remote_room_hosts opt…
t3chguy Aug 5, 2021
85c166e
Merge branch 'msc3266' of github.com:t3chguy/synapse into msc3266
t3chguy Aug 5, 2021
cc6c271
fix mypy lint and missing await
t3chguy Aug 5, 2021
0c5952b
delint s'more
t3chguy Aug 5, 2021
9e113aa
fix test_state by stubbing get_event_auth_handler
t3chguy Aug 5, 2021
faa8bf1
Merge branch 'develop' of https://github.com/matrix-org/synapse into …
t3chguy Aug 12, 2021
caa8015
re-apply consolidation between room_summary and space_summary
t3chguy Aug 12, 2021
f5c6740
delint
t3chguy Aug 12, 2021
2a9b961
Make requester optional to be more generically re-usable
t3chguy Aug 12, 2021
b277031
update naming and comments
t3chguy Aug 12, 2021
61d9312
Apply suggestions from code review
t3chguy Aug 13, 2021
dfa8247
remove references to summary
t3chguy Aug 13, 2021
9dbe660
Consolidate the two handlers into 1
t3chguy Aug 13, 2021
b7ba82a
Fix mocks
t3chguy Aug 13, 2021
7a57bcc
fix arg order
t3chguy Aug 13, 2021
8371e26
minimise diff
t3chguy Aug 13, 2021
d4020d8
delint
t3chguy Aug 13, 2021
3fbf621
revert bits of the PR
t3chguy Aug 13, 2021
e99ca29
revert s'more
t3chguy Aug 13, 2021
2823459
minimise diff
t3chguy Aug 13, 2021
82c6f40
Fix ordering of mypy.
clokep Aug 13, 2021
82ed39c
Update comments.
clokep Aug 13, 2021
0a74384
Rollback an unused change.
clokep Aug 13, 2021
5dcbf1a
Strip out code for federation, which is not yet supported.
clokep Aug 13, 2021
a168618
Pull in changes from #10569 to simplify code.
clokep Aug 13, 2021
d9c4e0c
Merge remote-tracking branch 'origin/develop' into msc3266
clokep Aug 16, 2021
4e23960
Inline a variable.
clokep Aug 16, 2021
a1f45e8
Merge remote-tracking branch 'origin/develop' into msc3266
clokep Aug 16, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/10394.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Initial local support for MSC3266, Room Summary over the unstable /rooms/{roomIdOrAlias}/summary API.
115 changes: 114 additions & 1 deletion synapse/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

from synapse import event_auth
from synapse.api.auth_blocking import AuthBlocking
from synapse.api.constants import EventTypes, HistoryVisibility, Membership
from synapse.api.constants import EventTypes, HistoryVisibility, JoinRules, Membership
from synapse.api.errors import (
AuthError,
Codes,
Expand Down Expand Up @@ -69,6 +69,7 @@ def __init__(self, hs: "HomeServer"):
)

self._auth_blocking = AuthBlocking(self.hs)
self._event_auth_handler = hs.get_event_auth_handler()

self._track_appservice_user_ips = hs.config.track_appservice_user_ips
self._macaroon_secret_key = hs.config.macaroon_secret_key
Expand Down Expand Up @@ -620,3 +621,115 @@ async def check_user_in_room_or_world_readable(

async def check_auth_blocking(self, *args, **kwargs) -> None:
await self._auth_blocking.check_auth_blocking(*args, **kwargs)

async def is_room_visible(
self, room_id: str, requester: Optional[str], origin: Optional[str] = None
) -> bool:
"""
Calculate whether the room should be shown to the requester.

It should return true if:

* The requester is joined or can join the room (per MSC3173).
* The origin server has any user that is joined or can join the room.
* The history visibility is set to world readable.

Args:
room_id: The room ID to check visibility of.
requester:
The user requesting the summary, if it is a local request.
None if this is a federation request.
origin:
The server requesting the summary, if it is a federation request.
None if this is a local request.

Returns:
True if the room should be visible to the requester.
"""
state_ids = await self.store.get_current_state_ids(room_id)

# If there's no state for the room, it isn't known.
if not state_ids:
# The user might have a pending invite for the room.
if requester and await self.store.get_invite_for_local_user_in_room(
requester, room_id
):
return True

logger.info("room %s is unknown, omitting from summary", room_id)
return False

room_version = await self.store.get_room_version(room_id)

# Include the room if it has join rules of public or knock.
join_rules_event_id = state_ids.get((EventTypes.JoinRules, ""))
if join_rules_event_id:
join_rules_event = await self.store.get_event(join_rules_event_id)
join_rule = join_rules_event.content.get("join_rule")
if join_rule == JoinRules.PUBLIC or (
room_version.msc2403_knocking and join_rule == JoinRules.KNOCK
):
return True

# Include the room if it is peekable.
hist_vis_event_id = state_ids.get((EventTypes.RoomHistoryVisibility, ""))
if hist_vis_event_id:
hist_vis_ev = await self.store.get_event(hist_vis_event_id)
hist_vis = hist_vis_ev.content.get("history_visibility")
if hist_vis == HistoryVisibility.WORLD_READABLE:
return True

# Otherwise we need to check information specific to the user or server.

# If we have an authenticated requesting user, check if they are a member
# of the room (or can join the room).
if requester:
member_event_id = state_ids.get((EventTypes.Member, requester), None)

# If they're in the room they can see info on it.
if member_event_id:
member_event = await self.store.get_event(member_event_id)
if member_event.membership in (Membership.JOIN, Membership.INVITE):
return True

# Otherwise, check if they should be allowed access via membership in a space.
if await self._event_auth_handler.has_restricted_join_rules(
state_ids, room_version
):
allowed_rooms = (
await self._event_auth_handler.get_rooms_that_allow_join(state_ids)
)
if await self._event_auth_handler.is_user_in_rooms(
allowed_rooms, requester
):
return True

# If this is a request over federation, check if the host is in the room or
# has a user who could join the room.
elif origin:
if await self._event_auth_handler.check_host_in_room(
room_id, origin
) or await self.store.is_host_invited(room_id, origin):
return True

# Alternately, if the host has a user in any of the spaces specified
# for access, then the host can see this room (and should do filtering
# if the requester cannot see it).
if await self._event_auth_handler.has_restricted_join_rules(
state_ids, room_version
):
allowed_rooms = (
await self._event_auth_handler.get_rooms_that_allow_join(state_ids)
)
for space_id in allowed_rooms:
if await self._event_auth_handler.check_host_in_room(
space_id, origin
):
return True

logger.info(
"room %s is unpeekable and requester %s is not a member / not allowed to join",
room_id,
requester or origin,
)
return False
3 changes: 3 additions & 0 deletions synapse/config/experimental.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,6 @@ def read_config(self, config: JsonDict, **kwargs):

# MSC3244 (room version capabilities)
self.msc3244_enabled: bool = experimental.get("msc3244_enabled", False)

# MSC3266 (room summary api)
self.msc3266_enabled: bool = experimental.get("msc3266_enabled", False)
131 changes: 131 additions & 0 deletions synapse/handlers/room_summary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Copyright 2021 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
from typing import TYPE_CHECKING, List, Optional

from synapse.api.errors import NotFoundError
from synapse.handlers.space_summary import RoomSummaryMixin
from synapse.types import JsonDict

if TYPE_CHECKING:
from synapse.server import HomeServer

logger = logging.getLogger(__name__)


class RoomSummaryHandler(RoomSummaryMixin):
def __init__(self, hs: "HomeServer"):
super().__init__(hs)
self._clock = hs.get_clock()
self._server_name = hs.hostname

async def get_room_summary(
self,
requester: Optional[str],
room_id: str,
remote_room_hosts: Optional[List[str]] = None,
) -> JsonDict:
"""
Implementation of the room summary C-S API MSC3266

Args:
requester: user id of the user making this request,
can be None for unauthenticated requests

room_id: room id to start the summary at

remote_room_hosts: a list of homeservers to try fetching data through
if we don't know it ourselves

Returns:
summary dict to return
"""
is_in_room = await self._store.is_host_joined(room_id, self._server_name)

if is_in_room:
room_summary = await self._summarize_local_room(requester, None, room_id)

if requester:
(
membership,
_,
) = await self._store.get_local_current_membership_for_user_in_room(
requester, room_id
)

room_summary["membership"] = membership or "leave"
else:
room_summary = await self._summarize_remote_room(room_id, remote_room_hosts)

# validate that the requester has permission to see this room
include_room = self._is_remote_room_accessible(
requester, room_id, room_summary
)

if not include_room:
raise NotFoundError("Room not found or is not accessible")

# Before returning to the client, remove the allowed_room_ids
# and allowed_spaces keys.
room_summary.pop("allowed_room_ids", None)
room_summary.pop("allowed_spaces", None)

return room_summary

async def _summarize_local_room(
self,
requester: Optional[str],
origin: Optional[str],
room_id: str,
) -> JsonDict:
"""
Generate a room entry and a list of event entries for a given room.

Args:
requester:
The user requesting the summary, if it is a local request. None
if this is a federation request.
origin:
The server requesting the summary, if it is a federation request.
None if this is a local request.
room_id: The room ID to summarize.

Returns:
summary dict to return
"""
if not await self._auth.is_room_visible(room_id, requester, origin):
raise NotFoundError("Room not found or is not accessible")

return await self._build_room_entry(room_id, for_federation=bool(origin))

async def _summarize_remote_room(
self,
room_id: str,
remote_room_hosts: Optional[List[str]],
) -> JsonDict:
"""
Request room entries and a list of event entries for a given room by querying a remote server.

Args:
room_id: The room to summarize.
remote_room_hosts: List of homeservers to attempt to fetch the data from.

Returns:
summary dict to return
"""
logger.info("Requesting summary for %s via %s", room_id, remote_room_hosts)

# TODO federation API, descoped from initial unstable implementation as MSC needs more maturing on that side.
raise NotFoundError("Room not found or is not accessible")
Loading