From fb9b3613cbbc37ab95e872ad75a5bc704b96ee54 Mon Sep 17 00:00:00 2001 From: David Robertson Date: Fri, 14 Oct 2022 00:11:30 +0100 Subject: [PATCH] Use Pydantic to validate `PUT /directory/list/room/{roomId}` --- synapse/handlers/directory.py | 10 +++++----- synapse/rest/client/directory.py | 9 ++++++--- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/synapse/handlers/directory.py b/synapse/handlers/directory.py index 7127d5aefcb7..d300e8e76406 100644 --- a/synapse/handlers/directory.py +++ b/synapse/handlers/directory.py @@ -14,7 +14,7 @@ import logging import string -from typing import TYPE_CHECKING, Iterable, List, Optional +from typing import TYPE_CHECKING, Iterable, List, Literal, Optional from synapse.api.constants import MAX_ALIAS_LENGTH, EventTypes from synapse.api.errors import ( @@ -429,7 +429,10 @@ async def _user_can_delete_alias( return await self.auth.check_can_change_room_list(room_id, requester) async def edit_published_room_list( - self, requester: Requester, room_id: str, visibility: str + self, + requester: Requester, + room_id: str, + visibility: Literal["public", "private"], ) -> None: """Edit the entry of the room in the published room list. @@ -451,9 +454,6 @@ async def edit_published_room_list( if requester.is_guest: raise AuthError(403, "Guests cannot edit the published room list") - if visibility not in ["public", "private"]: - raise SynapseError(400, "Invalid visibility setting") - if visibility == "public" and not self.enable_room_list_search: # The room list has been disabled. raise AuthError( diff --git a/synapse/rest/client/directory.py b/synapse/rest/client/directory.py index 306484d252bd..488541c443af 100644 --- a/synapse/rest/client/directory.py +++ b/synapse/rest/client/directory.py @@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, List, Optional, Tuple from pydantic import StrictStr +from typing_extensions import Literal from twisted.web.server import Request @@ -141,16 +142,18 @@ async def on_GET(self, request: Request, room_id: str) -> Tuple[int, JsonDict]: return 200, {"visibility": "public" if room["is_public"] else "private"} + class PutBody(RequestBodyModel): + visibility: Literal["public", "private"] = "public" + async def on_PUT( self, request: SynapseRequest, room_id: str ) -> Tuple[int, JsonDict]: requester = await self.auth.get_user_by_req(request) - content = parse_json_object_from_request(request) - visibility = content.get("visibility", "public") + content = parse_and_validate_json_object_from_request(request, self.PutBody) await self.directory_handler.edit_published_room_list( - requester, room_id, visibility + requester, room_id, content.visibility ) return 200, {}