Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
fix: health check middleware not forwarding non-HTTP requests (#17248)
Mikail7637b07ca303
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3da9d79aa6..1cbec002c4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -52,3 +52,4 @@ All notable, unreleased changes to this project will be documented in this file.- Fix undiscounted price taxation when prices are entered with taxes - #16992 by @zedzior- Fix `products` sorting when using `sortBy: {field: COLLECTION}` - #17189 by @korycins- Fix checkout funds releasing task - #17198 by @IKarbowiak+- Fixed 'healthcheck' middleware (`/health/` endpoint) not forwarding incoming traffic whenever the protocol wasn't HTTP (such as WebSocket or Lifespan) - #17248 by @NyanKiyoshidiff --git a/saleor/asgi/health_check.py b/saleor/asgi/health_check.pyindex b642674bdb..27c014912f 100644--- a/saleor/asgi/health_check.py+++ b/saleor/asgi/health_check.py@@ -12,9 +12,8 @@ def health_check(application: ASGI3Application, health_url: str) -> ASGI3Applicaasync def health_check_wrapper(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:- if scope.get("type") == "http" and scope.get("path") != health_url:- await application(scope, receive, send)- return+ if scope.get("type") != "http" or scope.get("path") != health_url:+ return await application(scope, receive, send)await send(HTTPResponseStartEvent(type="http.response.start",@@ -26,5 +25,6 @@ def health_check(application: ASGI3Application, health_url: str) -> ASGI3Applicaawait send(HTTPResponseBodyEvent(type="http.response.body", body=b"", more_body=False))+ return Nonereturn health_check_wrapperdiff --git a/saleor/asgi/tests/asgi_test_utils.py b/saleor/asgi/tests/asgi_test_utils.pynew file mode 100644index 0000000000..e4e40f8d5e--- /dev/null+++ b/saleor/asgi/tests/asgi_test_utils.py@@ -0,0 +1,36 @@+from asgiref.typing import Scope, WebSocketScope+from django.core.handlers.asgi import ASGIHandler+++class DummyASGIApplication(ASGIHandler):+ """A dummy ASGI application that always return a dummy string.++ Used to indicate it was called successfully.+ """++ RESPONSE_STRING = "Dummy ASGI Application: called."++ async def __call__(self, scope: Scope, receive, send):+ return self.RESPONSE_STRING+++def create_asgi_scope_websocket_proto(+ path: str, headers: list[tuple[bytes, bytes] | None] = None+) -> WebSocketScope:+ """Return a webhook protocol ASGI 3.0 scope."""+ return {+ "type": "websocket",+ "asgi": {"version": "3.0"},+ "path": path, # str+ # raw_path: the original HTTP path (w/o query string), unmodified from what was+ # received by the web server. Optional (nullable).+ "raw_path": path,+ # The root path this application is mounted at.+ "root_path": None,+ "headers": headers or [],+ "client": ("127.0.0.1", 0),+ "server": ("testserver", "80"),+ "subprotocols": [],+ "state": {},+ "extensions": None,+ }diff --git a/saleor/asgi/tests/test_healthcheck.py b/saleor/asgi/tests/test_healthcheck.pynew file mode 100644index 0000000000..688ad4ec05--- /dev/null+++ b/saleor/asgi/tests/test_healthcheck.py@@ -0,0 +1,46 @@+from unittest import mock++from saleor.asgi import health_check+from saleor.asgi.tests.asgi_test_utils import (+ DummyASGIApplication,+ create_asgi_scope_websocket_proto,+)+++async def test_non_http_requests_forwarded_to_next_wrapper():+ """Ensure the middleware forwards the request when the protocol isn't HTTP."""++ scope = create_asgi_scope_websocket_proto("/health/")+ handler = health_check(DummyASGIApplication(), health_url="/health/")++ # WebSocket protocol shouldn't return an empty response (healthcheck),+ # instead it should return the dummy response from the dummy ASGI application.+ response = await handler(scope, receive=None, send=None)+ assert response == DummyASGIApplication.RESPONSE_STRING++ # When protocol is HTTP, it should return the health check result+ # (HTTP 200 + empty body) instead of the dummy response (i.e., shouldn't forward the+ # request down the chain).+ scope["type"] = "http"+ send_callback = mock.AsyncMock()+ response = await handler(scope, receive=None, send=send_callback)+ # Shouldn't have returned anything (especially not the string from+ # DummyASGIApplication.RESPONSE_STRING)+ assert response is None+ assert send_callback.call_args_list == [+ mock.call(+ {+ "type": "http.response.start",+ "status": 200,+ "headers": [(b"content-type", b"text/plain")],+ "trailers": False,+ }+ ),+ mock.call(+ {+ "type": "http.response.body",+ "body": b"",+ "more_body": False,+ }+ ),+ ]