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

Commit

Permalink
Move check_user_in_room, check_user_in_room_or_world_readable, and ch…
Browse files Browse the repository at this point in the history
…eck_can_change_room_list to EventAuthHandler.
  • Loading branch information
clokep committed Jun 30, 2021
1 parent 12ae3d8 commit 3b07593
Show file tree
Hide file tree
Showing 11 changed files with 172 additions and 155 deletions.
134 changes: 2 additions & 132 deletions synapse/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,20 @@

from twisted.web.server import Request

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
from synapse.api.errors import (
AuthError,
Codes,
InvalidClientTokenError,
MissingClientTokenError,
)
from synapse.appservice import ApplicationService
from synapse.events import EventBase
from synapse.http import get_request_user_agent
from synapse.http.site import SynapseRequest
from synapse.logging import opentracing as opentracing
from synapse.storage.databases.main.registration import TokenLookupResult
from synapse.types import Requester, StateMap, UserID, create_requester
from synapse.types import Requester, UserID, create_requester
from synapse.util.caches.lrucache import LruCache
from synapse.util.macaroons import get_value_from_macaroon, satisfy_expiry

Expand Down Expand Up @@ -87,56 +85,6 @@ def __init__(self, hs: "HomeServer"):
self._macaroon_secret_key = hs.config.macaroon_secret_key
self._force_tracing_for_users = hs.config.tracing.force_tracing_for_users

async def check_user_in_room(
self,
room_id: str,
user_id: str,
current_state: Optional[StateMap[EventBase]] = None,
allow_departed_users: bool = False,
) -> EventBase:
"""Check if the user is in the room, or was at some point.
Args:
room_id: The room to check.
user_id: The user to check.
current_state: Optional map of the current state of the room.
If provided then that map is used to check whether they are a
member of the room. Otherwise the current membership is
loaded from the database.
allow_departed_users: if True, accept users that were previously
members but have now departed.
Raises:
AuthError if the user is/was not in the room.
Returns:
Membership event for the user if the user was in the
room. This will be the join event if they are currently joined to
the room. This will be the leave event if they have left the room.
"""
if current_state:
member = current_state.get((EventTypes.Member, user_id), None)
else:
member = await self.state.get_current_state(
room_id=room_id, event_type=EventTypes.Member, state_key=user_id
)

if member:
membership = member.membership

if membership == Membership.JOIN:
return member

# XXX this looks totally bogus. Why do we not allow users who have been banned,
# or those who were members previously and have been re-invited?
if allow_departed_users and membership == Membership.LEAVE:
forgot = await self.store.did_forget(user_id, room_id)
if not forgot:
return member

raise AuthError(403, "User %s not in room %s" % (user_id, room_id))

async def get_user_by_req(
self,
request: SynapseRequest,
Expand Down Expand Up @@ -467,40 +415,6 @@ async def is_server_admin(self, user: UserID) -> bool:
"""
return await self.store.is_server_admin(user)

async def check_can_change_room_list(self, room_id: str, user: UserID) -> bool:
"""Determine whether the user is allowed to edit the room's entry in the
published room list.
Args:
room_id
user
"""

is_admin = await self.is_server_admin(user)
if is_admin:
return True

user_id = user.to_string()
await self.check_user_in_room(room_id, user_id)

# We currently require the user is a "moderator" in the room. We do this
# by checking if they would (theoretically) be able to change the
# m.room.canonical_alias events
power_level_event = await self.state.get_current_state(
room_id, EventTypes.PowerLevels, ""
)

auth_events = {}
if power_level_event:
auth_events[(EventTypes.PowerLevels, "")] = power_level_event

send_level = event_auth.get_send_level(
EventTypes.CanonicalAlias, "", power_level_event
)
user_level = event_auth.get_user_power_level(user_id, auth_events)

return user_level >= send_level

@staticmethod
def has_access_token(request: Request) -> bool:
"""Checks if the request has an access_token.
Expand Down Expand Up @@ -553,49 +467,5 @@ def get_access_token_from_request(request: Request) -> str:

return query_params[0].decode("ascii")

async def check_user_in_room_or_world_readable(
self, room_id: str, user_id: str, allow_departed_users: bool = False
) -> Tuple[str, Optional[str]]:
"""Checks that the user is or was in the room or the room is world
readable. If it isn't then an exception is raised.
Args:
room_id: room to check
user_id: user to check
allow_departed_users: if True, accept users that were previously
members but have now departed
Returns:
Resolves to the current membership of the user in the room and the
membership event ID of the user. If the user is not in the room and
never has been, then `(Membership.JOIN, None)` is returned.
"""

try:
# check_user_in_room will return the most recent membership
# event for the user if:
# * The user is a non-guest user, and was ever in the room
# * The user is a guest user, and has joined the room
# else it will throw.
member_event = await self.check_user_in_room(
room_id, user_id, allow_departed_users=allow_departed_users
)
return member_event.membership, member_event.event_id
except AuthError:
visibility = await self.state.get_current_state(
room_id, EventTypes.RoomHistoryVisibility, ""
)
if (
visibility
and visibility.content.get("history_visibility")
== HistoryVisibility.WORLD_READABLE
):
return Membership.JOIN, None
raise AuthError(
403,
"User %s not in room %s, and room previews are disabled"
% (user_id, room_id),
)

async def check_auth_blocking(self, *args, **kwargs) -> None:
await self._auth_blocking.check_auth_blocking(*args, **kwargs)
10 changes: 7 additions & 3 deletions synapse/event_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
# limitations under the License.

import logging
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, Union

from canonicaljson import encode_canonical_json
from signedjson.key import decode_verify_key_bytes
Expand All @@ -29,9 +29,11 @@
RoomVersion,
)
from synapse.events import EventBase
from synapse.events.builder import EventBuilder
from synapse.types import StateMap, UserID, get_domain_from_id

if TYPE_CHECKING:
from synapse.events.builder import EventBuilder

logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -725,7 +727,9 @@ def get_public_keys(invite_event: EventBase) -> List[Dict[str, Any]]:
return public_keys


def auth_types_for_event(event: Union[EventBase, EventBuilder]) -> Set[Tuple[str, str]]:
def auth_types_for_event(
event: Union[EventBase, "EventBuilder"]
) -> Set[Tuple[str, str]]:
"""Given an event, return a list of (EventType, StateKey) that may be
needed to auth the event. The returned list may be a superset of what
would actually be required depending on the full state of the room.
Expand Down
11 changes: 7 additions & 4 deletions synapse/handlers/directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def __init__(self, hs: "HomeServer"):
self.state = hs.get_state_handler()
self.appservice_handler = hs.get_application_service_handler()
self.event_creation_handler = hs.get_event_creation_handler()
self._event_auth_handler = hs.get_event_auth_handler()
self.store = hs.get_datastore()
self.config = hs.config
self.enable_room_list_search = hs.config.enable_room_list_search
Expand Down Expand Up @@ -403,7 +404,7 @@ async def _user_can_delete_alias(self, alias: RoomAlias, user_id: str) -> bool:
if not room_id:
return False

return await self.auth.check_can_change_room_list(
return await self._event_auth_handler.check_can_change_room_list(
room_id, UserID.from_string(user_id)
)

Expand Down Expand Up @@ -439,8 +440,10 @@ async def edit_published_room_list(
if room is None:
raise SynapseError(400, "Unknown room")

can_change_room_list = await self.auth.check_can_change_room_list(
room_id, requester.user
can_change_room_list = (
await self._event_auth_handler.check_can_change_room_list(
room_id, requester.user
)
)
if not can_change_room_list:
raise AuthError(
Expand Down Expand Up @@ -503,7 +506,7 @@ async def get_aliases_for_room(
# allow access to server admins and current members of the room
is_admin = await self.auth.is_server_admin(requester.user)
if not is_admin:
await self.auth.check_user_in_room_or_world_readable(
await self._event_auth_handler.check_user_in_room_or_world_readable(
room_id, requester.user.to_string()
)

Expand Down
Loading

0 comments on commit 3b07593

Please sign in to comment.