Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return JSON error responses for unknown routes/methods. #55

Merged
merged 1 commit into from
Nov 29, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/matrix_content_scanner/httpserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,31 @@ async def simple_cors_middleware(
return response


@web.middleware
async def json_errors_middleware(
request: web.Request,
handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
"""A simple aiohttp middleware that converts 404/405 errors into Matrix JSON error.

Args:
request: The request to handle.
handler: The handler for this request.

Returns:
The original response OR a JSON error response.
"""
# Run the request's handler and append CORS headers to it.
try:
return await handler(request)
except (web.HTTPNotFound, web.HTTPMethodNotAllowed) as ex:
# Return the proper JSON response.
return web.json_response(
{"errcode": "M_UNRECOGNIZED", "error": "Unrecognized request"},
status=ex.status,
)


class HTTPServer:
def __init__(self, mcs: "MatrixContentScanner"):
self._mcs = mcs
Expand Down Expand Up @@ -117,6 +142,8 @@ def _build_app(self) -> web.Application:
web.normalize_path_middleware(),
# Handler CORS.
simple_cors_middleware,
# Convert unknown routes/methods into JSON errors.
json_errors_middleware,
],
)
root.add_subapp("/_matrix/media_proxy/unstable", app)
Expand Down
Loading