From fcb46a597270db602edffd68e8ef7275b021959a Mon Sep 17 00:00:00 2001 From: Anthony Lukach Date: Fri, 25 Jul 2025 11:06:57 -0700 Subject: [PATCH 1/3] fix(middleware): enhance JSON parsing error handling Added logging for JSON parsing errors in the JsonResponseMiddleware. If an invalid JSON is received, a 502 response is returned with an error message, improving error visibility and response management. --- src/stac_auth_proxy/utils/middleware.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/stac_auth_proxy/utils/middleware.py b/src/stac_auth_proxy/utils/middleware.py index db754493..780fa3bb 100644 --- a/src/stac_auth_proxy/utils/middleware.py +++ b/src/stac_auth_proxy/utils/middleware.py @@ -1,13 +1,17 @@ """Utilities for middleware response handling.""" import json +import logging from abc import ABC, abstractmethod from typing import Any, Optional from starlette.datastructures import MutableHeaders from starlette.requests import Request +from starlette.responses import JSONResponse from starlette.types import ASGIApp, Message, Receive, Scope, Send +logger = logging.getLogger(__name__) + class JsonResponseMiddleware(ABC): """Base class for middleware that transforms JSON response bodies.""" @@ -78,7 +82,18 @@ async def transform_response(message: Message) -> None: # Transform the JSON body if body: - data = json.loads(body) + try: + data = json.loads(body) + except json.JSONDecodeError as e: + logger.error("Error parsing JSON: %s", e) + logger.error("Body: %s", body) + logger.error("Response scope: %s", scope) + response = JSONResponse( + {"error": "Received invalid JSON from upstream serverso"}, + status_code=502, + ) + await response(scope, receive, send) + return transformed = self.transform_json(data, request=request) body = json.dumps(transformed).encode() From 5b06380350c052a342d86e17503554321166f5d5 Mon Sep 17 00:00:00 2001 From: Anthony Lukach Date: Fri, 25 Jul 2025 12:09:51 -0700 Subject: [PATCH 2/3] Update src/stac_auth_proxy/utils/middleware.py --- src/stac_auth_proxy/utils/middleware.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/stac_auth_proxy/utils/middleware.py b/src/stac_auth_proxy/utils/middleware.py index 780fa3bb..ca0f17b3 100644 --- a/src/stac_auth_proxy/utils/middleware.py +++ b/src/stac_auth_proxy/utils/middleware.py @@ -89,7 +89,7 @@ async def transform_response(message: Message) -> None: logger.error("Body: %s", body) logger.error("Response scope: %s", scope) response = JSONResponse( - {"error": "Received invalid JSON from upstream serverso"}, + {"error": "Received invalid JSON from upstream server"}, status_code=502, ) await response(scope, receive, send) From e222c9aba46ae296aa886b5f57caae795c25c481 Mon Sep 17 00:00:00 2001 From: Anthony Lukach Date: Tue, 2 Sep 2025 21:11:44 -0700 Subject: [PATCH 3/3] test: add unit test for handling invalid JSON from upstream server This test verifies that the middleware correctly returns a 502 error when invalid JSON is received from an upstream server, ensuring robust error handling in the application. --- tests/test_middleware.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/test_middleware.py b/tests/test_middleware.py index aca901ac..2d114c9a 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -101,3 +101,21 @@ async def test_endpoint(): assert response.status_code == 200 assert "text/plain" in response.headers["content-type"] assert response.text == "invalid json" + + +def test_json_response_middleware_invalid_json_upstream(): + """Test that invalid JSON from upstream server returns 502 error.""" + app = FastAPI() + app.add_middleware(ExampleJsonResponseMiddleware) + + @app.get("/test") + async def test_endpoint(): + # Return invalid JSON with JSON content type to trigger the error handling + return Response(content="invalid json content", media_type="application/json") + + client = TestClient(app) + response = client.get("/test") + assert response.status_code == 502 + assert response.headers["content-type"] == "application/json" + data = response.json() + assert data == {"error": "Received invalid JSON from upstream server"}