Convert status codes to `HTTPStatus` in `synapse.rest.admin` (#11452)

This commit is contained in:
Dirk Klimpel 2021-11-29 23:19:45 +01:00 committed by GitHub
parent fb58611d21
commit e8ae94a223
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 276 additions and 171 deletions

1
changelog.d/11452.misc Normal file
View File

@ -0,0 +1 @@
Convert status codes to `HTTPStatus` in `synapse.rest.admin`.

View File

@ -17,6 +17,7 @@
import logging import logging
import platform import platform
from http import HTTPStatus
from typing import TYPE_CHECKING, Optional, Tuple from typing import TYPE_CHECKING, Optional, Tuple
import synapse import synapse
@ -98,7 +99,7 @@ class VersionServlet(RestServlet):
} }
def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]: def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
return 200, self.res return HTTPStatus.OK, self.res
class PurgeHistoryRestServlet(RestServlet): class PurgeHistoryRestServlet(RestServlet):
@ -130,7 +131,7 @@ class PurgeHistoryRestServlet(RestServlet):
event = await self.store.get_event(event_id) event = await self.store.get_event(event_id)
if event.room_id != room_id: if event.room_id != room_id:
raise SynapseError(400, "Event is for wrong room.") raise SynapseError(HTTPStatus.BAD_REQUEST, "Event is for wrong room.")
# RoomStreamToken expects [int] not Optional[int] # RoomStreamToken expects [int] not Optional[int]
assert event.internal_metadata.stream_ordering is not None assert event.internal_metadata.stream_ordering is not None
@ -144,7 +145,9 @@ class PurgeHistoryRestServlet(RestServlet):
ts = body["purge_up_to_ts"] ts = body["purge_up_to_ts"]
if not isinstance(ts, int): if not isinstance(ts, int):
raise SynapseError( raise SynapseError(
400, "purge_up_to_ts must be an int", errcode=Codes.BAD_JSON HTTPStatus.BAD_REQUEST,
"purge_up_to_ts must be an int",
errcode=Codes.BAD_JSON,
) )
stream_ordering = await self.store.find_first_stream_ordering_after_ts(ts) stream_ordering = await self.store.find_first_stream_ordering_after_ts(ts)
@ -160,7 +163,9 @@ class PurgeHistoryRestServlet(RestServlet):
stream_ordering, stream_ordering,
) )
raise SynapseError( raise SynapseError(
404, "there is no event to be purged", errcode=Codes.NOT_FOUND HTTPStatus.NOT_FOUND,
"there is no event to be purged",
errcode=Codes.NOT_FOUND,
) )
(stream, topo, _event_id) = r (stream, topo, _event_id) = r
token = "t%d-%d" % (topo, stream) token = "t%d-%d" % (topo, stream)
@ -173,7 +178,7 @@ class PurgeHistoryRestServlet(RestServlet):
) )
else: else:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"must specify purge_up_to_event_id or purge_up_to_ts", "must specify purge_up_to_event_id or purge_up_to_ts",
errcode=Codes.BAD_JSON, errcode=Codes.BAD_JSON,
) )
@ -182,7 +187,7 @@ class PurgeHistoryRestServlet(RestServlet):
room_id, token, delete_local_events=delete_local_events room_id, token, delete_local_events=delete_local_events
) )
return 200, {"purge_id": purge_id} return HTTPStatus.OK, {"purge_id": purge_id}
class PurgeHistoryStatusRestServlet(RestServlet): class PurgeHistoryStatusRestServlet(RestServlet):
@ -201,7 +206,7 @@ class PurgeHistoryStatusRestServlet(RestServlet):
if purge_status is None: if purge_status is None:
raise NotFoundError("purge id '%s' not found" % purge_id) raise NotFoundError("purge id '%s' not found" % purge_id)
return 200, purge_status.asdict() return HTTPStatus.OK, purge_status.asdict()
######################################################################################## ########################################################################################

View File

@ -13,6 +13,7 @@
# limitations under the License. # limitations under the License.
import re import re
from http import HTTPStatus
from typing import Iterable, Pattern from typing import Iterable, Pattern
from synapse.api.auth import Auth from synapse.api.auth import Auth
@ -62,4 +63,4 @@ async def assert_user_is_admin(auth: Auth, user_id: UserID) -> None:
""" """
is_admin = await auth.is_server_admin(user_id) is_admin = await auth.is_server_admin(user_id)
if not is_admin: if not is_admin:
raise AuthError(403, "You are not a server admin") raise AuthError(HTTPStatus.FORBIDDEN, "You are not a server admin")

View File

@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import logging import logging
from http import HTTPStatus
from typing import TYPE_CHECKING, Tuple from typing import TYPE_CHECKING, Tuple
from synapse.api.errors import NotFoundError, SynapseError from synapse.api.errors import NotFoundError, SynapseError
@ -53,7 +54,7 @@ class DeviceRestServlet(RestServlet):
target_user = UserID.from_string(user_id) target_user = UserID.from_string(user_id)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Can only lookup local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only lookup local users")
u = await self.store.get_user_by_id(target_user.to_string()) u = await self.store.get_user_by_id(target_user.to_string())
if u is None: if u is None:
@ -62,7 +63,7 @@ class DeviceRestServlet(RestServlet):
device = await self.device_handler.get_device( device = await self.device_handler.get_device(
target_user.to_string(), device_id target_user.to_string(), device_id
) )
return 200, device return HTTPStatus.OK, device
async def on_DELETE( async def on_DELETE(
self, request: SynapseRequest, user_id: str, device_id: str self, request: SynapseRequest, user_id: str, device_id: str
@ -71,14 +72,14 @@ class DeviceRestServlet(RestServlet):
target_user = UserID.from_string(user_id) target_user = UserID.from_string(user_id)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Can only lookup local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only lookup local users")
u = await self.store.get_user_by_id(target_user.to_string()) u = await self.store.get_user_by_id(target_user.to_string())
if u is None: if u is None:
raise NotFoundError("Unknown user") raise NotFoundError("Unknown user")
await self.device_handler.delete_device(target_user.to_string(), device_id) await self.device_handler.delete_device(target_user.to_string(), device_id)
return 200, {} return HTTPStatus.OK, {}
async def on_PUT( async def on_PUT(
self, request: SynapseRequest, user_id: str, device_id: str self, request: SynapseRequest, user_id: str, device_id: str
@ -87,7 +88,7 @@ class DeviceRestServlet(RestServlet):
target_user = UserID.from_string(user_id) target_user = UserID.from_string(user_id)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Can only lookup local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only lookup local users")
u = await self.store.get_user_by_id(target_user.to_string()) u = await self.store.get_user_by_id(target_user.to_string())
if u is None: if u is None:
@ -97,7 +98,7 @@ class DeviceRestServlet(RestServlet):
await self.device_handler.update_device( await self.device_handler.update_device(
target_user.to_string(), device_id, body target_user.to_string(), device_id, body
) )
return 200, {} return HTTPStatus.OK, {}
class DevicesRestServlet(RestServlet): class DevicesRestServlet(RestServlet):
@ -124,14 +125,14 @@ class DevicesRestServlet(RestServlet):
target_user = UserID.from_string(user_id) target_user = UserID.from_string(user_id)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Can only lookup local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only lookup local users")
u = await self.store.get_user_by_id(target_user.to_string()) u = await self.store.get_user_by_id(target_user.to_string())
if u is None: if u is None:
raise NotFoundError("Unknown user") raise NotFoundError("Unknown user")
devices = await self.device_handler.get_devices_by_user(target_user.to_string()) devices = await self.device_handler.get_devices_by_user(target_user.to_string())
return 200, {"devices": devices, "total": len(devices)} return HTTPStatus.OK, {"devices": devices, "total": len(devices)}
class DeleteDevicesRestServlet(RestServlet): class DeleteDevicesRestServlet(RestServlet):
@ -155,7 +156,7 @@ class DeleteDevicesRestServlet(RestServlet):
target_user = UserID.from_string(user_id) target_user = UserID.from_string(user_id)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Can only lookup local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only lookup local users")
u = await self.store.get_user_by_id(target_user.to_string()) u = await self.store.get_user_by_id(target_user.to_string())
if u is None: if u is None:
@ -167,4 +168,4 @@ class DeleteDevicesRestServlet(RestServlet):
await self.device_handler.delete_devices( await self.device_handler.delete_devices(
target_user.to_string(), body["devices"] target_user.to_string(), body["devices"]
) )
return 200, {} return HTTPStatus.OK, {}

View File

@ -13,6 +13,7 @@
# limitations under the License. # limitations under the License.
import logging import logging
from http import HTTPStatus
from typing import TYPE_CHECKING, Tuple from typing import TYPE_CHECKING, Tuple
from synapse.api.errors import Codes, NotFoundError, SynapseError from synapse.api.errors import Codes, NotFoundError, SynapseError
@ -66,21 +67,23 @@ class EventReportsRestServlet(RestServlet):
if start < 0: if start < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"The start parameter must be a positive integer.", "The start parameter must be a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if limit < 0: if limit < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"The limit parameter must be a positive integer.", "The limit parameter must be a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if direction not in ("f", "b"): if direction not in ("f", "b"):
raise SynapseError( raise SynapseError(
400, "Unknown direction: %s" % (direction,), errcode=Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
"Unknown direction: %s" % (direction,),
errcode=Codes.INVALID_PARAM,
) )
event_reports, total = await self.store.get_event_reports_paginate( event_reports, total = await self.store.get_event_reports_paginate(
@ -90,7 +93,7 @@ class EventReportsRestServlet(RestServlet):
if (start + limit) < total: if (start + limit) < total:
ret["next_token"] = start + len(event_reports) ret["next_token"] = start + len(event_reports)
return 200, ret return HTTPStatus.OK, ret
class EventReportDetailRestServlet(RestServlet): class EventReportDetailRestServlet(RestServlet):
@ -127,13 +130,17 @@ class EventReportDetailRestServlet(RestServlet):
try: try:
resolved_report_id = int(report_id) resolved_report_id = int(report_id)
except ValueError: except ValueError:
raise SynapseError(400, message, errcode=Codes.INVALID_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM
)
if resolved_report_id < 0: if resolved_report_id < 0:
raise SynapseError(400, message, errcode=Codes.INVALID_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM
)
ret = await self.store.get_event_report(resolved_report_id) ret = await self.store.get_event_report(resolved_report_id)
if not ret: if not ret:
raise NotFoundError("Event report not found") raise NotFoundError("Event report not found")
return 200, ret return HTTPStatus.OK, ret

View File

@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import logging import logging
from http import HTTPStatus
from typing import TYPE_CHECKING, Tuple from typing import TYPE_CHECKING, Tuple
from synapse.api.errors import SynapseError from synapse.api.errors import SynapseError
@ -43,7 +44,7 @@ class DeleteGroupAdminRestServlet(RestServlet):
await assert_user_is_admin(self.auth, requester.user) await assert_user_is_admin(self.auth, requester.user)
if not self.is_mine_id(group_id): if not self.is_mine_id(group_id):
raise SynapseError(400, "Can only delete local groups") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only delete local groups")
await self.group_server.delete_group(group_id, requester.user.to_string()) await self.group_server.delete_group(group_id, requester.user.to_string())
return 200, {} return HTTPStatus.OK, {}

View File

@ -14,6 +14,7 @@
# limitations under the License. # limitations under the License.
import logging import logging
from http import HTTPStatus
from typing import TYPE_CHECKING, Tuple from typing import TYPE_CHECKING, Tuple
from synapse.api.errors import AuthError, Codes, NotFoundError, SynapseError from synapse.api.errors import AuthError, Codes, NotFoundError, SynapseError
@ -62,7 +63,7 @@ class QuarantineMediaInRoom(RestServlet):
room_id, requester.user.to_string() room_id, requester.user.to_string()
) )
return 200, {"num_quarantined": num_quarantined} return HTTPStatus.OK, {"num_quarantined": num_quarantined}
class QuarantineMediaByUser(RestServlet): class QuarantineMediaByUser(RestServlet):
@ -89,7 +90,7 @@ class QuarantineMediaByUser(RestServlet):
user_id, requester.user.to_string() user_id, requester.user.to_string()
) )
return 200, {"num_quarantined": num_quarantined} return HTTPStatus.OK, {"num_quarantined": num_quarantined}
class QuarantineMediaByID(RestServlet): class QuarantineMediaByID(RestServlet):
@ -118,7 +119,7 @@ class QuarantineMediaByID(RestServlet):
server_name, media_id, requester.user.to_string() server_name, media_id, requester.user.to_string()
) )
return 200, {} return HTTPStatus.OK, {}
class UnquarantineMediaByID(RestServlet): class UnquarantineMediaByID(RestServlet):
@ -147,7 +148,7 @@ class UnquarantineMediaByID(RestServlet):
# Remove from quarantine this media id # Remove from quarantine this media id
await self.store.quarantine_media_by_id(server_name, media_id, None) await self.store.quarantine_media_by_id(server_name, media_id, None)
return 200, {} return HTTPStatus.OK, {}
class ProtectMediaByID(RestServlet): class ProtectMediaByID(RestServlet):
@ -170,7 +171,7 @@ class ProtectMediaByID(RestServlet):
# Protect this media id # Protect this media id
await self.store.mark_local_media_as_safe(media_id, safe=True) await self.store.mark_local_media_as_safe(media_id, safe=True)
return 200, {} return HTTPStatus.OK, {}
class UnprotectMediaByID(RestServlet): class UnprotectMediaByID(RestServlet):
@ -193,7 +194,7 @@ class UnprotectMediaByID(RestServlet):
# Unprotect this media id # Unprotect this media id
await self.store.mark_local_media_as_safe(media_id, safe=False) await self.store.mark_local_media_as_safe(media_id, safe=False)
return 200, {} return HTTPStatus.OK, {}
class ListMediaInRoom(RestServlet): class ListMediaInRoom(RestServlet):
@ -211,11 +212,11 @@ class ListMediaInRoom(RestServlet):
requester = await self.auth.get_user_by_req(request) requester = await self.auth.get_user_by_req(request)
is_admin = await self.auth.is_server_admin(requester.user) is_admin = await self.auth.is_server_admin(requester.user)
if not is_admin: if not is_admin:
raise AuthError(403, "You are not a server admin") raise AuthError(HTTPStatus.FORBIDDEN, "You are not a server admin")
local_mxcs, remote_mxcs = await self.store.get_media_mxcs_in_room(room_id) local_mxcs, remote_mxcs = await self.store.get_media_mxcs_in_room(room_id)
return 200, {"local": local_mxcs, "remote": remote_mxcs} return HTTPStatus.OK, {"local": local_mxcs, "remote": remote_mxcs}
class PurgeMediaCacheRestServlet(RestServlet): class PurgeMediaCacheRestServlet(RestServlet):
@ -233,13 +234,13 @@ class PurgeMediaCacheRestServlet(RestServlet):
if before_ts < 0: if before_ts < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter before_ts must be a positive integer.", "Query parameter before_ts must be a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
elif before_ts < 30000000000: # Dec 1970 in milliseconds, Aug 2920 in seconds elif before_ts < 30000000000: # Dec 1970 in milliseconds, Aug 2920 in seconds
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter before_ts you provided is from the year 1970. " "Query parameter before_ts you provided is from the year 1970. "
+ "Double check that you are providing a timestamp in milliseconds.", + "Double check that you are providing a timestamp in milliseconds.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
@ -247,7 +248,7 @@ class PurgeMediaCacheRestServlet(RestServlet):
ret = await self.media_repository.delete_old_remote_media(before_ts) ret = await self.media_repository.delete_old_remote_media(before_ts)
return 200, ret return HTTPStatus.OK, ret
class DeleteMediaByID(RestServlet): class DeleteMediaByID(RestServlet):
@ -267,7 +268,7 @@ class DeleteMediaByID(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if self.server_name != server_name: if self.server_name != server_name:
raise SynapseError(400, "Can only delete local media") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only delete local media")
if await self.store.get_local_media(media_id) is None: if await self.store.get_local_media(media_id) is None:
raise NotFoundError("Unknown media") raise NotFoundError("Unknown media")
@ -277,7 +278,7 @@ class DeleteMediaByID(RestServlet):
deleted_media, total = await self.media_repository.delete_local_media_ids( deleted_media, total = await self.media_repository.delete_local_media_ids(
[media_id] [media_id]
) )
return 200, {"deleted_media": deleted_media, "total": total} return HTTPStatus.OK, {"deleted_media": deleted_media, "total": total}
class DeleteMediaByDateSize(RestServlet): class DeleteMediaByDateSize(RestServlet):
@ -304,26 +305,26 @@ class DeleteMediaByDateSize(RestServlet):
if before_ts < 0: if before_ts < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter before_ts must be a positive integer.", "Query parameter before_ts must be a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
elif before_ts < 30000000000: # Dec 1970 in milliseconds, Aug 2920 in seconds elif before_ts < 30000000000: # Dec 1970 in milliseconds, Aug 2920 in seconds
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter before_ts you provided is from the year 1970. " "Query parameter before_ts you provided is from the year 1970. "
+ "Double check that you are providing a timestamp in milliseconds.", + "Double check that you are providing a timestamp in milliseconds.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if size_gt < 0: if size_gt < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter size_gt must be a string representing a positive integer.", "Query parameter size_gt must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if self.server_name != server_name: if self.server_name != server_name:
raise SynapseError(400, "Can only delete local media") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only delete local media")
logging.info( logging.info(
"Deleting local media by timestamp: %s, size larger than: %s, keep profile media: %s" "Deleting local media by timestamp: %s, size larger than: %s, keep profile media: %s"
@ -333,7 +334,7 @@ class DeleteMediaByDateSize(RestServlet):
deleted_media, total = await self.media_repository.delete_old_local_media( deleted_media, total = await self.media_repository.delete_old_local_media(
before_ts, size_gt, keep_profiles before_ts, size_gt, keep_profiles
) )
return 200, {"deleted_media": deleted_media, "total": total} return HTTPStatus.OK, {"deleted_media": deleted_media, "total": total}
class UserMediaRestServlet(RestServlet): class UserMediaRestServlet(RestServlet):
@ -369,7 +370,7 @@ class UserMediaRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if not self.is_mine(UserID.from_string(user_id)): if not self.is_mine(UserID.from_string(user_id)):
raise SynapseError(400, "Can only look up local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
user = await self.store.get_user_by_id(user_id) user = await self.store.get_user_by_id(user_id)
if user is None: if user is None:
@ -380,14 +381,14 @@ class UserMediaRestServlet(RestServlet):
if start < 0: if start < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter from must be a string representing a positive integer.", "Query parameter from must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if limit < 0: if limit < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter limit must be a string representing a positive integer.", "Query parameter limit must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -425,7 +426,7 @@ class UserMediaRestServlet(RestServlet):
if (start + limit) < total: if (start + limit) < total:
ret["next_token"] = start + len(media) ret["next_token"] = start + len(media)
return 200, ret return HTTPStatus.OK, ret
async def on_DELETE( async def on_DELETE(
self, request: SynapseRequest, user_id: str self, request: SynapseRequest, user_id: str
@ -436,7 +437,7 @@ class UserMediaRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if not self.is_mine(UserID.from_string(user_id)): if not self.is_mine(UserID.from_string(user_id)):
raise SynapseError(400, "Can only look up local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
user = await self.store.get_user_by_id(user_id) user = await self.store.get_user_by_id(user_id)
if user is None: if user is None:
@ -447,14 +448,14 @@ class UserMediaRestServlet(RestServlet):
if start < 0: if start < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter from must be a string representing a positive integer.", "Query parameter from must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if limit < 0: if limit < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter limit must be a string representing a positive integer.", "Query parameter limit must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -492,7 +493,7 @@ class UserMediaRestServlet(RestServlet):
([row["media_id"] for row in media]) ([row["media_id"] for row in media])
) )
return 200, {"deleted_media": deleted_media, "total": total} return HTTPStatus.OK, {"deleted_media": deleted_media, "total": total}
def register_servlets_for_media_repo(hs: "HomeServer", http_server: HttpServer) -> None: def register_servlets_for_media_repo(hs: "HomeServer", http_server: HttpServer) -> None:

View File

@ -14,6 +14,7 @@
import logging import logging
import string import string
from http import HTTPStatus
from typing import TYPE_CHECKING, Tuple from typing import TYPE_CHECKING, Tuple
from synapse.api.errors import Codes, NotFoundError, SynapseError from synapse.api.errors import Codes, NotFoundError, SynapseError
@ -77,7 +78,7 @@ class ListRegistrationTokensRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
valid = parse_boolean(request, "valid") valid = parse_boolean(request, "valid")
token_list = await self.store.get_registration_tokens(valid) token_list = await self.store.get_registration_tokens(valid)
return 200, {"registration_tokens": token_list} return HTTPStatus.OK, {"registration_tokens": token_list}
class NewRegistrationTokenRestServlet(RestServlet): class NewRegistrationTokenRestServlet(RestServlet):
@ -123,16 +124,20 @@ class NewRegistrationTokenRestServlet(RestServlet):
if "token" in body: if "token" in body:
token = body["token"] token = body["token"]
if not isinstance(token, str): if not isinstance(token, str):
raise SynapseError(400, "token must be a string", Codes.INVALID_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST,
"token must be a string",
Codes.INVALID_PARAM,
)
if not (0 < len(token) <= 64): if not (0 < len(token) <= 64):
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"token must not be empty and must not be longer than 64 characters", "token must not be empty and must not be longer than 64 characters",
Codes.INVALID_PARAM, Codes.INVALID_PARAM,
) )
if not set(token).issubset(self.allowed_chars_set): if not set(token).issubset(self.allowed_chars_set):
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"token must consist only of characters matched by the regex [A-Za-z0-9-_]", "token must consist only of characters matched by the regex [A-Za-z0-9-_]",
Codes.INVALID_PARAM, Codes.INVALID_PARAM,
) )
@ -142,11 +147,13 @@ class NewRegistrationTokenRestServlet(RestServlet):
length = body.get("length", 16) length = body.get("length", 16)
if not isinstance(length, int): if not isinstance(length, int):
raise SynapseError( raise SynapseError(
400, "length must be an integer", Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
"length must be an integer",
Codes.INVALID_PARAM,
) )
if not (0 < length <= 64): if not (0 < length <= 64):
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"length must be greater than zero and not greater than 64", "length must be greater than zero and not greater than 64",
Codes.INVALID_PARAM, Codes.INVALID_PARAM,
) )
@ -162,7 +169,7 @@ class NewRegistrationTokenRestServlet(RestServlet):
or (isinstance(uses_allowed, int) and uses_allowed >= 0) or (isinstance(uses_allowed, int) and uses_allowed >= 0)
): ):
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"uses_allowed must be a non-negative integer or null", "uses_allowed must be a non-negative integer or null",
Codes.INVALID_PARAM, Codes.INVALID_PARAM,
) )
@ -170,11 +177,15 @@ class NewRegistrationTokenRestServlet(RestServlet):
expiry_time = body.get("expiry_time", None) expiry_time = body.get("expiry_time", None)
if not isinstance(expiry_time, (int, type(None))): if not isinstance(expiry_time, (int, type(None))):
raise SynapseError( raise SynapseError(
400, "expiry_time must be an integer or null", Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
"expiry_time must be an integer or null",
Codes.INVALID_PARAM,
) )
if isinstance(expiry_time, int) and expiry_time < self.clock.time_msec(): if isinstance(expiry_time, int) and expiry_time < self.clock.time_msec():
raise SynapseError( raise SynapseError(
400, "expiry_time must not be in the past", Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
"expiry_time must not be in the past",
Codes.INVALID_PARAM,
) )
created = await self.store.create_registration_token( created = await self.store.create_registration_token(
@ -182,7 +193,9 @@ class NewRegistrationTokenRestServlet(RestServlet):
) )
if not created: if not created:
raise SynapseError( raise SynapseError(
400, f"Token already exists: {token}", Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
f"Token already exists: {token}",
Codes.INVALID_PARAM,
) )
resp = { resp = {
@ -192,7 +205,7 @@ class NewRegistrationTokenRestServlet(RestServlet):
"completed": 0, "completed": 0,
"expiry_time": expiry_time, "expiry_time": expiry_time,
} }
return 200, resp return HTTPStatus.OK, resp
class RegistrationTokenRestServlet(RestServlet): class RegistrationTokenRestServlet(RestServlet):
@ -261,7 +274,7 @@ class RegistrationTokenRestServlet(RestServlet):
if token_info is None: if token_info is None:
raise NotFoundError(f"No such registration token: {token}") raise NotFoundError(f"No such registration token: {token}")
return 200, token_info return HTTPStatus.OK, token_info
async def on_PUT(self, request: SynapseRequest, token: str) -> Tuple[int, JsonDict]: async def on_PUT(self, request: SynapseRequest, token: str) -> Tuple[int, JsonDict]:
"""Update a registration token.""" """Update a registration token."""
@ -277,7 +290,7 @@ class RegistrationTokenRestServlet(RestServlet):
or (isinstance(uses_allowed, int) and uses_allowed >= 0) or (isinstance(uses_allowed, int) and uses_allowed >= 0)
): ):
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"uses_allowed must be a non-negative integer or null", "uses_allowed must be a non-negative integer or null",
Codes.INVALID_PARAM, Codes.INVALID_PARAM,
) )
@ -287,11 +300,15 @@ class RegistrationTokenRestServlet(RestServlet):
expiry_time = body["expiry_time"] expiry_time = body["expiry_time"]
if not isinstance(expiry_time, (int, type(None))): if not isinstance(expiry_time, (int, type(None))):
raise SynapseError( raise SynapseError(
400, "expiry_time must be an integer or null", Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
"expiry_time must be an integer or null",
Codes.INVALID_PARAM,
) )
if isinstance(expiry_time, int) and expiry_time < self.clock.time_msec(): if isinstance(expiry_time, int) and expiry_time < self.clock.time_msec():
raise SynapseError( raise SynapseError(
400, "expiry_time must not be in the past", Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
"expiry_time must not be in the past",
Codes.INVALID_PARAM,
) )
new_attributes["expiry_time"] = expiry_time new_attributes["expiry_time"] = expiry_time
@ -307,7 +324,7 @@ class RegistrationTokenRestServlet(RestServlet):
if token_info is None: if token_info is None:
raise NotFoundError(f"No such registration token: {token}") raise NotFoundError(f"No such registration token: {token}")
return 200, token_info return HTTPStatus.OK, token_info
async def on_DELETE( async def on_DELETE(
self, request: SynapseRequest, token: str self, request: SynapseRequest, token: str
@ -316,6 +333,6 @@ class RegistrationTokenRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if await self.store.delete_registration_token(token): if await self.store.delete_registration_token(token):
return 200, {} return HTTPStatus.OK, {}
raise NotFoundError(f"No such registration token: {token}") raise NotFoundError(f"No such registration token: {token}")

View File

@ -102,7 +102,9 @@ class RoomRestV2Servlet(RestServlet):
) )
if not RoomID.is_valid(room_id): if not RoomID.is_valid(room_id):
raise SynapseError(400, "%s is not a legal room ID" % (room_id,)) raise SynapseError(
HTTPStatus.BAD_REQUEST, "%s is not a legal room ID" % (room_id,)
)
if not await self._store.get_room(room_id): if not await self._store.get_room(room_id):
raise NotFoundError("Unknown room id %s" % (room_id,)) raise NotFoundError("Unknown room id %s" % (room_id,))
@ -118,7 +120,7 @@ class RoomRestV2Servlet(RestServlet):
force_purge=force_purge, force_purge=force_purge,
) )
return 200, {"delete_id": delete_id} return HTTPStatus.OK, {"delete_id": delete_id}
class DeleteRoomStatusByRoomIdRestServlet(RestServlet): class DeleteRoomStatusByRoomIdRestServlet(RestServlet):
@ -137,7 +139,9 @@ class DeleteRoomStatusByRoomIdRestServlet(RestServlet):
await assert_requester_is_admin(self._auth, request) await assert_requester_is_admin(self._auth, request)
if not RoomID.is_valid(room_id): if not RoomID.is_valid(room_id):
raise SynapseError(400, "%s is not a legal room ID" % (room_id,)) raise SynapseError(
HTTPStatus.BAD_REQUEST, "%s is not a legal room ID" % (room_id,)
)
delete_ids = self._pagination_handler.get_delete_ids_by_room(room_id) delete_ids = self._pagination_handler.get_delete_ids_by_room(room_id)
if delete_ids is None: if delete_ids is None:
@ -153,7 +157,7 @@ class DeleteRoomStatusByRoomIdRestServlet(RestServlet):
**delete.asdict(), **delete.asdict(),
} }
] ]
return 200, {"results": cast(JsonDict, response)} return HTTPStatus.OK, {"results": cast(JsonDict, response)}
class DeleteRoomStatusByDeleteIdRestServlet(RestServlet): class DeleteRoomStatusByDeleteIdRestServlet(RestServlet):
@ -175,7 +179,7 @@ class DeleteRoomStatusByDeleteIdRestServlet(RestServlet):
if delete_status is None: if delete_status is None:
raise NotFoundError("delete id '%s' not found" % delete_id) raise NotFoundError("delete id '%s' not found" % delete_id)
return 200, cast(JsonDict, delete_status.asdict()) return HTTPStatus.OK, cast(JsonDict, delete_status.asdict())
class ListRoomRestServlet(RestServlet): class ListRoomRestServlet(RestServlet):
@ -217,7 +221,7 @@ class ListRoomRestServlet(RestServlet):
RoomSortOrder.STATE_EVENTS.value, RoomSortOrder.STATE_EVENTS.value,
): ):
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Unknown value for order_by: %s" % (order_by,), "Unknown value for order_by: %s" % (order_by,),
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -225,7 +229,7 @@ class ListRoomRestServlet(RestServlet):
search_term = parse_string(request, "search_term", encoding="utf-8") search_term = parse_string(request, "search_term", encoding="utf-8")
if search_term == "": if search_term == "":
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"search_term cannot be an empty string", "search_term cannot be an empty string",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -233,7 +237,9 @@ class ListRoomRestServlet(RestServlet):
direction = parse_string(request, "dir", default="f") direction = parse_string(request, "dir", default="f")
if direction not in ("f", "b"): if direction not in ("f", "b"):
raise SynapseError( raise SynapseError(
400, "Unknown direction: %s" % (direction,), errcode=Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
"Unknown direction: %s" % (direction,),
errcode=Codes.INVALID_PARAM,
) )
reverse_order = True if direction == "b" else False reverse_order = True if direction == "b" else False
@ -265,7 +271,7 @@ class ListRoomRestServlet(RestServlet):
else: else:
response["prev_batch"] = 0 response["prev_batch"] = 0
return 200, response return HTTPStatus.OK, response
class RoomRestServlet(RestServlet): class RoomRestServlet(RestServlet):
@ -310,7 +316,7 @@ class RoomRestServlet(RestServlet):
members = await self.store.get_users_in_room(room_id) members = await self.store.get_users_in_room(room_id)
ret["joined_local_devices"] = await self.store.count_devices_by_users(members) ret["joined_local_devices"] = await self.store.count_devices_by_users(members)
return 200, ret return HTTPStatus.OK, ret
async def on_DELETE( async def on_DELETE(
self, request: SynapseRequest, room_id: str self, request: SynapseRequest, room_id: str
@ -386,7 +392,7 @@ class RoomRestServlet(RestServlet):
# See https://github.com/python/mypy/issues/4976#issuecomment-579883622 # See https://github.com/python/mypy/issues/4976#issuecomment-579883622
# for some discussion on why this is necessary. Either way, # for some discussion on why this is necessary. Either way,
# `ret` is an opaque dictionary blob as far as the rest of the app cares. # `ret` is an opaque dictionary blob as far as the rest of the app cares.
return 200, cast(JsonDict, ret) return HTTPStatus.OK, cast(JsonDict, ret)
class RoomMembersRestServlet(RestServlet): class RoomMembersRestServlet(RestServlet):
@ -413,7 +419,7 @@ class RoomMembersRestServlet(RestServlet):
members = await self.store.get_users_in_room(room_id) members = await self.store.get_users_in_room(room_id)
ret = {"members": members, "total": len(members)} ret = {"members": members, "total": len(members)}
return 200, ret return HTTPStatus.OK, ret
class RoomStateRestServlet(RestServlet): class RoomStateRestServlet(RestServlet):
@ -452,7 +458,7 @@ class RoomStateRestServlet(RestServlet):
) )
ret = {"state": room_state} ret = {"state": room_state}
return 200, ret return HTTPStatus.OK, ret
class JoinRoomAliasServlet(ResolveRoomIdMixin, RestServlet): class JoinRoomAliasServlet(ResolveRoomIdMixin, RestServlet):
@ -481,7 +487,10 @@ class JoinRoomAliasServlet(ResolveRoomIdMixin, RestServlet):
target_user = UserID.from_string(content["user_id"]) target_user = UserID.from_string(content["user_id"])
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "This endpoint can only be used with local users") raise SynapseError(
HTTPStatus.BAD_REQUEST,
"This endpoint can only be used with local users",
)
if not await self.admin_handler.get_user(target_user): if not await self.admin_handler.get_user(target_user):
raise NotFoundError("User not found") raise NotFoundError("User not found")
@ -527,7 +536,7 @@ class JoinRoomAliasServlet(ResolveRoomIdMixin, RestServlet):
ratelimit=False, ratelimit=False,
) )
return 200, {"room_id": room_id} return HTTPStatus.OK, {"room_id": room_id}
class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet): class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
@ -568,7 +577,7 @@ class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
# Figure out which local users currently have power in the room, if any. # Figure out which local users currently have power in the room, if any.
room_state = await self.state_handler.get_current_state(room_id) room_state = await self.state_handler.get_current_state(room_id)
if not room_state: if not room_state:
raise SynapseError(400, "Server not in room") raise SynapseError(HTTPStatus.BAD_REQUEST, "Server not in room")
create_event = room_state[(EventTypes.Create, "")] create_event = room_state[(EventTypes.Create, "")]
power_levels = room_state.get((EventTypes.PowerLevels, "")) power_levels = room_state.get((EventTypes.PowerLevels, ""))
@ -582,7 +591,9 @@ class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
admin_users.sort(key=lambda user: user_power[user]) admin_users.sort(key=lambda user: user_power[user])
if not admin_users: if not admin_users:
raise SynapseError(400, "No local admin user in room") raise SynapseError(
HTTPStatus.BAD_REQUEST, "No local admin user in room"
)
admin_user_id = None admin_user_id = None
@ -599,7 +610,7 @@ class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
if not admin_user_id: if not admin_user_id:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"No local admin user in room", "No local admin user in room",
) )
@ -610,7 +621,7 @@ class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
admin_user_id = create_event.sender admin_user_id = create_event.sender
if not self.is_mine_id(admin_user_id): if not self.is_mine_id(admin_user_id):
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"No local admin user in room", "No local admin user in room",
) )
@ -639,7 +650,8 @@ class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
except AuthError: except AuthError:
# The admin user we found turned out not to have enough power. # The admin user we found turned out not to have enough power.
raise SynapseError( raise SynapseError(
400, "No local admin user in room with power to update power levels." HTTPStatus.BAD_REQUEST,
"No local admin user in room with power to update power levels.",
) )
# Now we check if the user we're granting admin rights to is already in # Now we check if the user we're granting admin rights to is already in
@ -653,7 +665,7 @@ class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
) )
if is_joined: if is_joined:
return 200, {} return HTTPStatus.OK, {}
join_rules = room_state.get((EventTypes.JoinRules, "")) join_rules = room_state.get((EventTypes.JoinRules, ""))
is_public = False is_public = False
@ -661,7 +673,7 @@ class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
is_public = join_rules.content.get("join_rule") == JoinRules.PUBLIC is_public = join_rules.content.get("join_rule") == JoinRules.PUBLIC
if is_public: if is_public:
return 200, {} return HTTPStatus.OK, {}
await self.room_member_handler.update_membership( await self.room_member_handler.update_membership(
fake_requester, fake_requester,
@ -670,7 +682,7 @@ class MakeRoomAdminRestServlet(ResolveRoomIdMixin, RestServlet):
action=Membership.INVITE, action=Membership.INVITE,
) )
return 200, {} return HTTPStatus.OK, {}
class ForwardExtremitiesRestServlet(ResolveRoomIdMixin, RestServlet): class ForwardExtremitiesRestServlet(ResolveRoomIdMixin, RestServlet):
@ -702,7 +714,7 @@ class ForwardExtremitiesRestServlet(ResolveRoomIdMixin, RestServlet):
room_id, _ = await self.resolve_room_id(room_identifier) room_id, _ = await self.resolve_room_id(room_identifier)
deleted_count = await self.store.delete_forward_extremities_for_room(room_id) deleted_count = await self.store.delete_forward_extremities_for_room(room_id)
return 200, {"deleted": deleted_count} return HTTPStatus.OK, {"deleted": deleted_count}
async def on_GET( async def on_GET(
self, request: SynapseRequest, room_identifier: str self, request: SynapseRequest, room_identifier: str
@ -713,7 +725,7 @@ class ForwardExtremitiesRestServlet(ResolveRoomIdMixin, RestServlet):
room_id, _ = await self.resolve_room_id(room_identifier) room_id, _ = await self.resolve_room_id(room_identifier)
extremities = await self.store.get_forward_extremities_for_room(room_id) extremities = await self.store.get_forward_extremities_for_room(room_id)
return 200, {"count": len(extremities), "results": extremities} return HTTPStatus.OK, {"count": len(extremities), "results": extremities}
class RoomEventContextServlet(RestServlet): class RoomEventContextServlet(RestServlet):
@ -762,7 +774,9 @@ class RoomEventContextServlet(RestServlet):
) )
if not results: if not results:
raise SynapseError(404, "Event not found.", errcode=Codes.NOT_FOUND) raise SynapseError(
HTTPStatus.NOT_FOUND, "Event not found.", errcode=Codes.NOT_FOUND
)
time_now = self.clock.time_msec() time_now = self.clock.time_msec()
results["events_before"] = await self._event_serializer.serialize_events( results["events_before"] = await self._event_serializer.serialize_events(
@ -781,7 +795,7 @@ class RoomEventContextServlet(RestServlet):
bundle_relations=False, bundle_relations=False,
) )
return 200, results return HTTPStatus.OK, results
class BlockRoomRestServlet(RestServlet): class BlockRoomRestServlet(RestServlet):

View File

@ -11,6 +11,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from http import HTTPStatus
from typing import TYPE_CHECKING, Awaitable, Optional, Tuple from typing import TYPE_CHECKING, Awaitable, Optional, Tuple
from synapse.api.constants import EventTypes from synapse.api.constants import EventTypes
@ -82,11 +83,15 @@ class SendServerNoticeServlet(RestServlet):
# but worker processes still need to initialise SendServerNoticeServlet (as it is part of the # but worker processes still need to initialise SendServerNoticeServlet (as it is part of the
# admin api). # admin api).
if not self.server_notices_manager.is_enabled(): if not self.server_notices_manager.is_enabled():
raise SynapseError(400, "Server notices are not enabled on this server") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Server notices are not enabled on this server"
)
target_user = UserID.from_string(body["user_id"]) target_user = UserID.from_string(body["user_id"])
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Server notices can only be sent to local users") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Server notices can only be sent to local users"
)
if not await self.admin_handler.get_user(target_user): if not await self.admin_handler.get_user(target_user):
raise NotFoundError("User not found") raise NotFoundError("User not found")
@ -99,7 +104,7 @@ class SendServerNoticeServlet(RestServlet):
txn_id=txn_id, txn_id=txn_id,
) )
return 200, {"event_id": event.event_id} return HTTPStatus.OK, {"event_id": event.event_id}
def on_PUT( def on_PUT(
self, request: SynapseRequest, txn_id: str self, request: SynapseRequest, txn_id: str

View File

@ -13,6 +13,7 @@
# limitations under the License. # limitations under the License.
import logging import logging
from http import HTTPStatus
from typing import TYPE_CHECKING, Tuple from typing import TYPE_CHECKING, Tuple
from synapse.api.errors import Codes, SynapseError from synapse.api.errors import Codes, SynapseError
@ -53,7 +54,7 @@ class UserMediaStatisticsRestServlet(RestServlet):
UserSortOrder.DISPLAYNAME.value, UserSortOrder.DISPLAYNAME.value,
): ):
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Unknown value for order_by: %s" % (order_by,), "Unknown value for order_by: %s" % (order_by,),
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -61,7 +62,7 @@ class UserMediaStatisticsRestServlet(RestServlet):
start = parse_integer(request, "from", default=0) start = parse_integer(request, "from", default=0)
if start < 0: if start < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter from must be a string representing a positive integer.", "Query parameter from must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -69,7 +70,7 @@ class UserMediaStatisticsRestServlet(RestServlet):
limit = parse_integer(request, "limit", default=100) limit = parse_integer(request, "limit", default=100)
if limit < 0: if limit < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter limit must be a string representing a positive integer.", "Query parameter limit must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -77,7 +78,7 @@ class UserMediaStatisticsRestServlet(RestServlet):
from_ts = parse_integer(request, "from_ts", default=0) from_ts = parse_integer(request, "from_ts", default=0)
if from_ts < 0: if from_ts < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter from_ts must be a string representing a positive integer.", "Query parameter from_ts must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -86,13 +87,13 @@ class UserMediaStatisticsRestServlet(RestServlet):
if until_ts is not None: if until_ts is not None:
if until_ts < 0: if until_ts < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter until_ts must be a string representing a positive integer.", "Query parameter until_ts must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if until_ts <= from_ts: if until_ts <= from_ts:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter until_ts must be greater than from_ts.", "Query parameter until_ts must be greater than from_ts.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -100,7 +101,7 @@ class UserMediaStatisticsRestServlet(RestServlet):
search_term = parse_string(request, "search_term") search_term = parse_string(request, "search_term")
if search_term == "": if search_term == "":
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter search_term cannot be an empty string.", "Query parameter search_term cannot be an empty string.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -108,7 +109,9 @@ class UserMediaStatisticsRestServlet(RestServlet):
direction = parse_string(request, "dir", default="f") direction = parse_string(request, "dir", default="f")
if direction not in ("f", "b"): if direction not in ("f", "b"):
raise SynapseError( raise SynapseError(
400, "Unknown direction: %s" % (direction,), errcode=Codes.INVALID_PARAM HTTPStatus.BAD_REQUEST,
"Unknown direction: %s" % (direction,),
errcode=Codes.INVALID_PARAM,
) )
users_media, total = await self.store.get_users_media_usage_paginate( users_media, total = await self.store.get_users_media_usage_paginate(
@ -118,4 +121,4 @@ class UserMediaStatisticsRestServlet(RestServlet):
if (start + limit) < total: if (start + limit) < total:
ret["next_token"] = start + len(users_media) ret["next_token"] = start + len(users_media)
return 200, ret return HTTPStatus.OK, ret

View File

@ -79,14 +79,14 @@ class UsersRestServletV2(RestServlet):
if start < 0: if start < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter from must be a string representing a positive integer.", "Query parameter from must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if limit < 0: if limit < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Query parameter limit must be a string representing a positive integer.", "Query parameter limit must be a string representing a positive integer.",
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -122,7 +122,7 @@ class UsersRestServletV2(RestServlet):
if (start + limit) < total: if (start + limit) < total:
ret["next_token"] = str(start + len(users)) ret["next_token"] = str(start + len(users))
return 200, ret return HTTPStatus.OK, ret
class UserRestServletV2(RestServlet): class UserRestServletV2(RestServlet):
@ -172,14 +172,14 @@ class UserRestServletV2(RestServlet):
target_user = UserID.from_string(user_id) target_user = UserID.from_string(user_id)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Can only look up local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
ret = await self.admin_handler.get_user(target_user) ret = await self.admin_handler.get_user(target_user)
if not ret: if not ret:
raise NotFoundError("User not found") raise NotFoundError("User not found")
return 200, ret return HTTPStatus.OK, ret
async def on_PUT( async def on_PUT(
self, request: SynapseRequest, user_id: str self, request: SynapseRequest, user_id: str
@ -191,7 +191,10 @@ class UserRestServletV2(RestServlet):
body = parse_json_object_from_request(request) body = parse_json_object_from_request(request)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "This endpoint can only be used with local users") raise SynapseError(
HTTPStatus.BAD_REQUEST,
"This endpoint can only be used with local users",
)
user = await self.admin_handler.get_user(target_user) user = await self.admin_handler.get_user(target_user)
user_id = target_user.to_string() user_id = target_user.to_string()
@ -210,7 +213,7 @@ class UserRestServletV2(RestServlet):
user_type = body.get("user_type", None) user_type = body.get("user_type", None)
if user_type is not None and user_type not in UserTypes.ALL_USER_TYPES: if user_type is not None and user_type not in UserTypes.ALL_USER_TYPES:
raise SynapseError(400, "Invalid user type") raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid user type")
set_admin_to = body.get("admin", False) set_admin_to = body.get("admin", False)
if not isinstance(set_admin_to, bool): if not isinstance(set_admin_to, bool):
@ -223,11 +226,13 @@ class UserRestServletV2(RestServlet):
password = body.get("password", None) password = body.get("password", None)
if password is not None: if password is not None:
if not isinstance(password, str) or len(password) > 512: if not isinstance(password, str) or len(password) > 512:
raise SynapseError(400, "Invalid password") raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid password")
deactivate = body.get("deactivated", False) deactivate = body.get("deactivated", False)
if not isinstance(deactivate, bool): if not isinstance(deactivate, bool):
raise SynapseError(400, "'deactivated' parameter is not of type boolean") raise SynapseError(
HTTPStatus.BAD_REQUEST, "'deactivated' parameter is not of type boolean"
)
# convert List[Dict[str, str]] into List[Tuple[str, str]] # convert List[Dict[str, str]] into List[Tuple[str, str]]
if external_ids is not None: if external_ids is not None:
@ -282,7 +287,9 @@ class UserRestServletV2(RestServlet):
user_id, user_id,
) )
except ExternalIDReuseException: except ExternalIDReuseException:
raise SynapseError(409, "External id is already in use.") raise SynapseError(
HTTPStatus.CONFLICT, "External id is already in use."
)
if "avatar_url" in body and isinstance(body["avatar_url"], str): if "avatar_url" in body and isinstance(body["avatar_url"], str):
await self.profile_handler.set_avatar_url( await self.profile_handler.set_avatar_url(
@ -293,7 +300,9 @@ class UserRestServletV2(RestServlet):
if set_admin_to != user["admin"]: if set_admin_to != user["admin"]:
auth_user = requester.user auth_user = requester.user
if target_user == auth_user and not set_admin_to: if target_user == auth_user and not set_admin_to:
raise SynapseError(400, "You may not demote yourself.") raise SynapseError(
HTTPStatus.BAD_REQUEST, "You may not demote yourself."
)
await self.store.set_server_admin(target_user, set_admin_to) await self.store.set_server_admin(target_user, set_admin_to)
@ -319,7 +328,8 @@ class UserRestServletV2(RestServlet):
and self.auth_handler.can_change_password() and self.auth_handler.can_change_password()
): ):
raise SynapseError( raise SynapseError(
400, "Must provide a password to re-activate an account." HTTPStatus.BAD_REQUEST,
"Must provide a password to re-activate an account.",
) )
await self.deactivate_account_handler.activate_account( await self.deactivate_account_handler.activate_account(
@ -332,7 +342,7 @@ class UserRestServletV2(RestServlet):
user = await self.admin_handler.get_user(target_user) user = await self.admin_handler.get_user(target_user)
assert user is not None assert user is not None
return 200, user return HTTPStatus.OK, user
else: # create user else: # create user
displayname = body.get("displayname", None) displayname = body.get("displayname", None)
@ -381,7 +391,9 @@ class UserRestServletV2(RestServlet):
user_id, user_id,
) )
except ExternalIDReuseException: except ExternalIDReuseException:
raise SynapseError(409, "External id is already in use.") raise SynapseError(
HTTPStatus.CONFLICT, "External id is already in use."
)
if "avatar_url" in body and isinstance(body["avatar_url"], str): if "avatar_url" in body and isinstance(body["avatar_url"], str):
await self.profile_handler.set_avatar_url( await self.profile_handler.set_avatar_url(
@ -429,51 +441,61 @@ class UserRegisterServlet(RestServlet):
nonce = secrets.token_hex(64) nonce = secrets.token_hex(64)
self.nonces[nonce] = int(self.reactor.seconds()) self.nonces[nonce] = int(self.reactor.seconds())
return 200, {"nonce": nonce} return HTTPStatus.OK, {"nonce": nonce}
async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]: async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
self._clear_old_nonces() self._clear_old_nonces()
if not self.hs.config.registration.registration_shared_secret: if not self.hs.config.registration.registration_shared_secret:
raise SynapseError(400, "Shared secret registration is not enabled") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Shared secret registration is not enabled"
)
body = parse_json_object_from_request(request) body = parse_json_object_from_request(request)
if "nonce" not in body: if "nonce" not in body:
raise SynapseError(400, "nonce must be specified", errcode=Codes.BAD_JSON) raise SynapseError(
HTTPStatus.BAD_REQUEST,
"nonce must be specified",
errcode=Codes.BAD_JSON,
)
nonce = body["nonce"] nonce = body["nonce"]
if nonce not in self.nonces: if nonce not in self.nonces:
raise SynapseError(400, "unrecognised nonce") raise SynapseError(HTTPStatus.BAD_REQUEST, "unrecognised nonce")
# Delete the nonce, so it can't be reused, even if it's invalid # Delete the nonce, so it can't be reused, even if it's invalid
del self.nonces[nonce] del self.nonces[nonce]
if "username" not in body: if "username" not in body:
raise SynapseError( raise SynapseError(
400, "username must be specified", errcode=Codes.BAD_JSON HTTPStatus.BAD_REQUEST,
"username must be specified",
errcode=Codes.BAD_JSON,
) )
else: else:
if not isinstance(body["username"], str) or len(body["username"]) > 512: if not isinstance(body["username"], str) or len(body["username"]) > 512:
raise SynapseError(400, "Invalid username") raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid username")
username = body["username"].encode("utf-8") username = body["username"].encode("utf-8")
if b"\x00" in username: if b"\x00" in username:
raise SynapseError(400, "Invalid username") raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid username")
if "password" not in body: if "password" not in body:
raise SynapseError( raise SynapseError(
400, "password must be specified", errcode=Codes.BAD_JSON HTTPStatus.BAD_REQUEST,
"password must be specified",
errcode=Codes.BAD_JSON,
) )
else: else:
password = body["password"] password = body["password"]
if not isinstance(password, str) or len(password) > 512: if not isinstance(password, str) or len(password) > 512:
raise SynapseError(400, "Invalid password") raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid password")
password_bytes = password.encode("utf-8") password_bytes = password.encode("utf-8")
if b"\x00" in password_bytes: if b"\x00" in password_bytes:
raise SynapseError(400, "Invalid password") raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid password")
password_hash = await self.auth_handler.hash(password) password_hash = await self.auth_handler.hash(password)
@ -482,10 +504,12 @@ class UserRegisterServlet(RestServlet):
displayname = body.get("displayname", None) displayname = body.get("displayname", None)
if user_type is not None and user_type not in UserTypes.ALL_USER_TYPES: if user_type is not None and user_type not in UserTypes.ALL_USER_TYPES:
raise SynapseError(400, "Invalid user type") raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid user type")
if "mac" not in body: if "mac" not in body:
raise SynapseError(400, "mac must be specified", errcode=Codes.BAD_JSON) raise SynapseError(
HTTPStatus.BAD_REQUEST, "mac must be specified", errcode=Codes.BAD_JSON
)
got_mac = body["mac"] got_mac = body["mac"]
@ -507,7 +531,7 @@ class UserRegisterServlet(RestServlet):
want_mac = want_mac_builder.hexdigest() want_mac = want_mac_builder.hexdigest()
if not hmac.compare_digest(want_mac.encode("ascii"), got_mac.encode("ascii")): if not hmac.compare_digest(want_mac.encode("ascii"), got_mac.encode("ascii")):
raise SynapseError(403, "HMAC incorrect") raise SynapseError(HTTPStatus.FORBIDDEN, "HMAC incorrect")
# Reuse the parts of RegisterRestServlet to reduce code duplication # Reuse the parts of RegisterRestServlet to reduce code duplication
from synapse.rest.client.register import RegisterRestServlet from synapse.rest.client.register import RegisterRestServlet
@ -524,7 +548,7 @@ class UserRegisterServlet(RestServlet):
) )
result = await register._create_registration_details(user_id, body) result = await register._create_registration_details(user_id, body)
return 200, result return HTTPStatus.OK, result
class WhoisRestServlet(RestServlet): class WhoisRestServlet(RestServlet):
@ -552,11 +576,11 @@ class WhoisRestServlet(RestServlet):
await assert_user_is_admin(self.auth, auth_user) await assert_user_is_admin(self.auth, auth_user)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Can only whois a local user") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only whois a local user")
ret = await self.admin_handler.get_whois(target_user) ret = await self.admin_handler.get_whois(target_user)
return 200, ret return HTTPStatus.OK, ret
class DeactivateAccountRestServlet(RestServlet): class DeactivateAccountRestServlet(RestServlet):
@ -575,7 +599,9 @@ class DeactivateAccountRestServlet(RestServlet):
await assert_user_is_admin(self.auth, requester.user) await assert_user_is_admin(self.auth, requester.user)
if not self.is_mine(UserID.from_string(target_user_id)): if not self.is_mine(UserID.from_string(target_user_id)):
raise SynapseError(400, "Can only deactivate local users") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Can only deactivate local users"
)
if not await self.store.get_user_by_id(target_user_id): if not await self.store.get_user_by_id(target_user_id):
raise NotFoundError("User not found") raise NotFoundError("User not found")
@ -597,7 +623,7 @@ class DeactivateAccountRestServlet(RestServlet):
else: else:
id_server_unbind_result = "no-support" id_server_unbind_result = "no-support"
return 200, {"id_server_unbind_result": id_server_unbind_result} return HTTPStatus.OK, {"id_server_unbind_result": id_server_unbind_result}
class AccountValidityRenewServlet(RestServlet): class AccountValidityRenewServlet(RestServlet):
@ -620,7 +646,7 @@ class AccountValidityRenewServlet(RestServlet):
if "user_id" not in body: if "user_id" not in body:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"Missing property 'user_id' in the request body", "Missing property 'user_id' in the request body",
) )
@ -631,7 +657,7 @@ class AccountValidityRenewServlet(RestServlet):
) )
res = {"expiration_ts": expiration_ts} res = {"expiration_ts": expiration_ts}
return 200, res return HTTPStatus.OK, res
class ResetPasswordRestServlet(RestServlet): class ResetPasswordRestServlet(RestServlet):
@ -678,7 +704,7 @@ class ResetPasswordRestServlet(RestServlet):
await self._set_password_handler.set_password( await self._set_password_handler.set_password(
target_user_id, new_password_hash, logout_devices, requester target_user_id, new_password_hash, logout_devices, requester
) )
return 200, {} return HTTPStatus.OK, {}
class SearchUsersRestServlet(RestServlet): class SearchUsersRestServlet(RestServlet):
@ -712,16 +738,16 @@ class SearchUsersRestServlet(RestServlet):
# To allow all users to get the users list # To allow all users to get the users list
# if not is_admin and target_user != auth_user: # if not is_admin and target_user != auth_user:
# raise AuthError(403, "You are not a server admin") # raise AuthError(HTTPStatus.FORBIDDEN, "You are not a server admin")
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Can only users a local user") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only users a local user")
term = parse_string(request, "term", required=True) term = parse_string(request, "term", required=True)
logger.info("term: %s ", term) logger.info("term: %s ", term)
ret = await self.store.search_users(term) ret = await self.store.search_users(term)
return 200, ret return HTTPStatus.OK, ret
class UserAdminServlet(RestServlet): class UserAdminServlet(RestServlet):
@ -765,11 +791,14 @@ class UserAdminServlet(RestServlet):
target_user = UserID.from_string(user_id) target_user = UserID.from_string(user_id)
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Only local users can be admins of this homeserver") raise SynapseError(
HTTPStatus.BAD_REQUEST,
"Only local users can be admins of this homeserver",
)
is_admin = await self.store.is_server_admin(target_user) is_admin = await self.store.is_server_admin(target_user)
return 200, {"admin": is_admin} return HTTPStatus.OK, {"admin": is_admin}
async def on_PUT( async def on_PUT(
self, request: SynapseRequest, user_id: str self, request: SynapseRequest, user_id: str
@ -785,16 +814,19 @@ class UserAdminServlet(RestServlet):
assert_params_in_dict(body, ["admin"]) assert_params_in_dict(body, ["admin"])
if not self.hs.is_mine(target_user): if not self.hs.is_mine(target_user):
raise SynapseError(400, "Only local users can be admins of this homeserver") raise SynapseError(
HTTPStatus.BAD_REQUEST,
"Only local users can be admins of this homeserver",
)
set_admin_to = bool(body["admin"]) set_admin_to = bool(body["admin"])
if target_user == auth_user and not set_admin_to: if target_user == auth_user and not set_admin_to:
raise SynapseError(400, "You may not demote yourself.") raise SynapseError(HTTPStatus.BAD_REQUEST, "You may not demote yourself.")
await self.store.set_server_admin(target_user, set_admin_to) await self.store.set_server_admin(target_user, set_admin_to)
return 200, {} return HTTPStatus.OK, {}
class UserMembershipRestServlet(RestServlet): class UserMembershipRestServlet(RestServlet):
@ -816,7 +848,7 @@ class UserMembershipRestServlet(RestServlet):
room_ids = await self.store.get_rooms_for_user(user_id) room_ids = await self.store.get_rooms_for_user(user_id)
ret = {"joined_rooms": list(room_ids), "total": len(room_ids)} ret = {"joined_rooms": list(room_ids), "total": len(room_ids)}
return 200, ret return HTTPStatus.OK, ret
class PushersRestServlet(RestServlet): class PushersRestServlet(RestServlet):
@ -845,7 +877,7 @@ class PushersRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if not self.is_mine(UserID.from_string(user_id)): if not self.is_mine(UserID.from_string(user_id)):
raise SynapseError(400, "Can only look up local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
if not await self.store.get_user_by_id(user_id): if not await self.store.get_user_by_id(user_id):
raise NotFoundError("User not found") raise NotFoundError("User not found")
@ -854,7 +886,10 @@ class PushersRestServlet(RestServlet):
filtered_pushers = [p.as_dict() for p in pushers] filtered_pushers = [p.as_dict() for p in pushers]
return 200, {"pushers": filtered_pushers, "total": len(filtered_pushers)} return HTTPStatus.OK, {
"pushers": filtered_pushers,
"total": len(filtered_pushers),
}
class UserTokenRestServlet(RestServlet): class UserTokenRestServlet(RestServlet):
@ -887,16 +922,22 @@ class UserTokenRestServlet(RestServlet):
auth_user = requester.user auth_user = requester.user
if not self.hs.is_mine_id(user_id): if not self.hs.is_mine_id(user_id):
raise SynapseError(400, "Only local users can be logged in as") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Only local users can be logged in as"
)
body = parse_json_object_from_request(request, allow_empty_body=True) body = parse_json_object_from_request(request, allow_empty_body=True)
valid_until_ms = body.get("valid_until_ms") valid_until_ms = body.get("valid_until_ms")
if valid_until_ms and not isinstance(valid_until_ms, int): if valid_until_ms and not isinstance(valid_until_ms, int):
raise SynapseError(400, "'valid_until_ms' parameter must be an int") raise SynapseError(
HTTPStatus.BAD_REQUEST, "'valid_until_ms' parameter must be an int"
)
if auth_user.to_string() == user_id: if auth_user.to_string() == user_id:
raise SynapseError(400, "Cannot use admin API to login as self") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Cannot use admin API to login as self"
)
token = await self.auth_handler.create_access_token_for_user_id( token = await self.auth_handler.create_access_token_for_user_id(
user_id=auth_user.to_string(), user_id=auth_user.to_string(),
@ -905,7 +946,7 @@ class UserTokenRestServlet(RestServlet):
puppets_user_id=user_id, puppets_user_id=user_id,
) )
return 200, {"access_token": token} return HTTPStatus.OK, {"access_token": token}
class ShadowBanRestServlet(RestServlet): class ShadowBanRestServlet(RestServlet):
@ -947,11 +988,13 @@ class ShadowBanRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if not self.hs.is_mine_id(user_id): if not self.hs.is_mine_id(user_id):
raise SynapseError(400, "Only local users can be shadow-banned") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Only local users can be shadow-banned"
)
await self.store.set_shadow_banned(UserID.from_string(user_id), True) await self.store.set_shadow_banned(UserID.from_string(user_id), True)
return 200, {} return HTTPStatus.OK, {}
async def on_DELETE( async def on_DELETE(
self, request: SynapseRequest, user_id: str self, request: SynapseRequest, user_id: str
@ -959,11 +1002,13 @@ class ShadowBanRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if not self.hs.is_mine_id(user_id): if not self.hs.is_mine_id(user_id):
raise SynapseError(400, "Only local users can be shadow-banned") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Only local users can be shadow-banned"
)
await self.store.set_shadow_banned(UserID.from_string(user_id), False) await self.store.set_shadow_banned(UserID.from_string(user_id), False)
return 200, {} return HTTPStatus.OK, {}
class RateLimitRestServlet(RestServlet): class RateLimitRestServlet(RestServlet):
@ -995,7 +1040,7 @@ class RateLimitRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if not self.hs.is_mine_id(user_id): if not self.hs.is_mine_id(user_id):
raise SynapseError(400, "Can only look up local users") raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
if not await self.store.get_user_by_id(user_id): if not await self.store.get_user_by_id(user_id):
raise NotFoundError("User not found") raise NotFoundError("User not found")
@ -1016,7 +1061,7 @@ class RateLimitRestServlet(RestServlet):
else: else:
ret = {} ret = {}
return 200, ret return HTTPStatus.OK, ret
async def on_POST( async def on_POST(
self, request: SynapseRequest, user_id: str self, request: SynapseRequest, user_id: str
@ -1024,7 +1069,9 @@ class RateLimitRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if not self.hs.is_mine_id(user_id): if not self.hs.is_mine_id(user_id):
raise SynapseError(400, "Only local users can be ratelimited") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Only local users can be ratelimited"
)
if not await self.store.get_user_by_id(user_id): if not await self.store.get_user_by_id(user_id):
raise NotFoundError("User not found") raise NotFoundError("User not found")
@ -1036,14 +1083,14 @@ class RateLimitRestServlet(RestServlet):
if not isinstance(messages_per_second, int) or messages_per_second < 0: if not isinstance(messages_per_second, int) or messages_per_second < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"%r parameter must be a positive int" % (messages_per_second,), "%r parameter must be a positive int" % (messages_per_second,),
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
if not isinstance(burst_count, int) or burst_count < 0: if not isinstance(burst_count, int) or burst_count < 0:
raise SynapseError( raise SynapseError(
400, HTTPStatus.BAD_REQUEST,
"%r parameter must be a positive int" % (burst_count,), "%r parameter must be a positive int" % (burst_count,),
errcode=Codes.INVALID_PARAM, errcode=Codes.INVALID_PARAM,
) )
@ -1059,7 +1106,7 @@ class RateLimitRestServlet(RestServlet):
"burst_count": ratelimit.burst_count, "burst_count": ratelimit.burst_count,
} }
return 200, ret return HTTPStatus.OK, ret
async def on_DELETE( async def on_DELETE(
self, request: SynapseRequest, user_id: str self, request: SynapseRequest, user_id: str
@ -1067,11 +1114,13 @@ class RateLimitRestServlet(RestServlet):
await assert_requester_is_admin(self.auth, request) await assert_requester_is_admin(self.auth, request)
if not self.hs.is_mine_id(user_id): if not self.hs.is_mine_id(user_id):
raise SynapseError(400, "Only local users can be ratelimited") raise SynapseError(
HTTPStatus.BAD_REQUEST, "Only local users can be ratelimited"
)
if not await self.store.get_user_by_id(user_id): if not await self.store.get_user_by_id(user_id):
raise NotFoundError("User not found") raise NotFoundError("User not found")
await self.store.delete_ratelimit_for_user(user_id) await self.store.delete_ratelimit_for_user(user_id)
return 200, {} return HTTPStatus.OK, {}