Use HTTPStatus constants in place of literals in synapse.http (#11543)

This commit is contained in:
Dirk Klimpel 2021-12-09 12:58:25 +01:00 committed by GitHub
parent b47d10dc46
commit 941ebe49ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 47 additions and 19 deletions

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

@ -0,0 +1 @@
Use HTTPStatus constants in place of literals in `synapse.http`.

View File

@ -14,6 +14,7 @@
# limitations under the License. # limitations under the License.
import logging import logging
import urllib.parse import urllib.parse
from http import HTTPStatus
from io import BytesIO from io import BytesIO
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
@ -280,7 +281,9 @@ class BlacklistingAgentWrapper(Agent):
ip_address, self._ip_whitelist, self._ip_blacklist ip_address, self._ip_whitelist, self._ip_blacklist
): ):
logger.info("Blocking access to %s due to blacklist" % (ip_address,)) logger.info("Blocking access to %s due to blacklist" % (ip_address,))
e = SynapseError(403, "IP address blocked by IP blacklist entry") e = SynapseError(
HTTPStatus.FORBIDDEN, "IP address blocked by IP blacklist entry"
)
return defer.fail(Failure(e)) return defer.fail(Failure(e))
return self._agent.request( return self._agent.request(
@ -719,7 +722,9 @@ class SimpleHttpClient:
if response.code > 299: if response.code > 299:
logger.warning("Got %d when downloading %s" % (response.code, url)) logger.warning("Got %d when downloading %s" % (response.code, url))
raise SynapseError(502, "Got error %d" % (response.code,), Codes.UNKNOWN) raise SynapseError(
HTTPStatus.BAD_GATEWAY, "Got error %d" % (response.code,), Codes.UNKNOWN
)
# TODO: if our Content-Type is HTML or something, just read the first # TODO: if our Content-Type is HTML or something, just read the first
# N bytes into RAM rather than saving it all to disk only to read it # N bytes into RAM rather than saving it all to disk only to read it
@ -731,12 +736,14 @@ class SimpleHttpClient:
) )
except BodyExceededMaxSize: except BodyExceededMaxSize:
raise SynapseError( raise SynapseError(
502, HTTPStatus.BAD_GATEWAY,
"Requested file is too large > %r bytes" % (max_size,), "Requested file is too large > %r bytes" % (max_size,),
Codes.TOO_LARGE, Codes.TOO_LARGE,
) )
except Exception as e: except Exception as e:
raise SynapseError(502, ("Failed to download remote body: %s" % e)) from e raise SynapseError(
HTTPStatus.BAD_GATEWAY, ("Failed to download remote body: %s" % e)
) from e
return ( return (
length, length,

View File

@ -19,6 +19,7 @@ import random
import sys import sys
import typing import typing
import urllib.parse import urllib.parse
from http import HTTPStatus
from io import BytesIO, StringIO from io import BytesIO, StringIO
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
@ -1154,7 +1155,7 @@ class MatrixFederationHttpClient:
request.destination, request.destination,
msg, msg,
) )
raise SynapseError(502, msg, Codes.TOO_LARGE) raise SynapseError(HTTPStatus.BAD_GATEWAY, msg, Codes.TOO_LARGE)
except defer.TimeoutError as e: except defer.TimeoutError as e:
logger.warning( logger.warning(
"{%s} [%s] Timed out reading response - %s %s", "{%s} [%s] Timed out reading response - %s %s",

View File

@ -14,6 +14,7 @@
""" This module contains base REST classes for constructing REST servlets. """ """ This module contains base REST classes for constructing REST servlets. """
import logging import logging
from http import HTTPStatus
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Iterable, Iterable,
@ -137,11 +138,15 @@ def parse_integer_from_args(
return int(args[name_bytes][0]) return int(args[name_bytes][0])
except Exception: except Exception:
message = "Query parameter %r must be an integer" % (name,) message = "Query parameter %r must be an integer" % (name,)
raise SynapseError(400, message, errcode=Codes.INVALID_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM
)
else: else:
if required: if required:
message = "Missing integer query parameter %r" % (name,) message = "Missing integer query parameter %r" % (name,)
raise SynapseError(400, message, errcode=Codes.MISSING_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
)
else: else:
return default return default
@ -246,11 +251,15 @@ def parse_boolean_from_args(
message = ( message = (
"Boolean query parameter %r must be one of ['true', 'false']" "Boolean query parameter %r must be one of ['true', 'false']"
) % (name,) ) % (name,)
raise SynapseError(400, message, errcode=Codes.INVALID_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM
)
else: else:
if required: if required:
message = "Missing boolean query parameter %r" % (name,) message = "Missing boolean query parameter %r" % (name,)
raise SynapseError(400, message, errcode=Codes.MISSING_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
)
else: else:
return default return default
@ -313,7 +322,7 @@ def parse_bytes_from_args(
return args[name_bytes][0] return args[name_bytes][0]
elif required: elif required:
message = "Missing string query parameter %s" % (name,) message = "Missing string query parameter %s" % (name,)
raise SynapseError(400, message, errcode=Codes.MISSING_PARAM) raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM)
return default return default
@ -407,14 +416,16 @@ def _parse_string_value(
try: try:
value_str = value.decode(encoding) value_str = value.decode(encoding)
except ValueError: except ValueError:
raise SynapseError(400, "Query parameter %r must be %s" % (name, encoding)) raise SynapseError(
HTTPStatus.BAD_REQUEST, "Query parameter %r must be %s" % (name, encoding)
)
if allowed_values is not None and value_str not in allowed_values: if allowed_values is not None and value_str not in allowed_values:
message = "Query parameter %r must be one of [%s]" % ( message = "Query parameter %r must be one of [%s]" % (
name, name,
", ".join(repr(v) for v in allowed_values), ", ".join(repr(v) for v in allowed_values),
) )
raise SynapseError(400, message, errcode=Codes.INVALID_PARAM) raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM)
else: else:
return value_str return value_str
@ -510,7 +521,9 @@ def parse_strings_from_args(
else: else:
if required: if required:
message = "Missing string query parameter %r" % (name,) message = "Missing string query parameter %r" % (name,)
raise SynapseError(400, message, errcode=Codes.MISSING_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
)
return default return default
@ -638,7 +651,7 @@ def parse_json_value_from_request(
try: try:
content_bytes = request.content.read() # type: ignore content_bytes = request.content.read() # type: ignore
except Exception: except Exception:
raise SynapseError(400, "Error reading JSON content.") raise SynapseError(HTTPStatus.BAD_REQUEST, "Error reading JSON content.")
if not content_bytes and allow_empty_body: if not content_bytes and allow_empty_body:
return None return None
@ -647,7 +660,9 @@ def parse_json_value_from_request(
content = json_decoder.decode(content_bytes.decode("utf-8")) content = json_decoder.decode(content_bytes.decode("utf-8"))
except Exception as e: except Exception as e:
logger.warning("Unable to parse JSON: %s (%s)", e, content_bytes) logger.warning("Unable to parse JSON: %s (%s)", e, content_bytes)
raise SynapseError(400, "Content not JSON.", errcode=Codes.NOT_JSON) raise SynapseError(
HTTPStatus.BAD_REQUEST, "Content not JSON.", errcode=Codes.NOT_JSON
)
return content return content
@ -673,7 +688,7 @@ def parse_json_object_from_request(
if not isinstance(content, dict): if not isinstance(content, dict):
message = "Content must be a JSON object." message = "Content must be a JSON object."
raise SynapseError(400, message, errcode=Codes.BAD_JSON) raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.BAD_JSON)
return content return content
@ -685,7 +700,9 @@ def assert_params_in_dict(body: JsonDict, required: Iterable[str]) -> None:
absent.append(k) absent.append(k)
if len(absent) > 0: if len(absent) > 0:
raise SynapseError(400, "Missing params: %r" % absent, Codes.MISSING_PARAM) raise SynapseError(
HTTPStatus.BAD_REQUEST, "Missing params: %r" % absent, Codes.MISSING_PARAM
)
class RestServlet: class RestServlet:
@ -758,10 +775,12 @@ class ResolveRoomIdMixin:
resolved_room_id = room_id.to_string() resolved_room_id = room_id.to_string()
else: else:
raise SynapseError( raise SynapseError(
400, "%s was not legal room ID or room alias" % (room_identifier,) HTTPStatus.BAD_REQUEST,
"%s was not legal room ID or room alias" % (room_identifier,),
) )
if not resolved_room_id: if not resolved_room_id:
raise SynapseError( raise SynapseError(
400, "Unknown room ID or room alias %s" % room_identifier HTTPStatus.BAD_REQUEST,
"Unknown room ID or room alias %s" % room_identifier,
) )
return resolved_room_id, remote_room_hosts return resolved_room_id, remote_room_hosts