Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add missing support for simple requests in the CORS flow (#12000)

Patryk Zawadzki55ff6b5b2b65
diff --git a/saleor/asgi/cors_handler.py b/saleor/asgi/cors_handler.py
index 8c514c5657..44b75f0b4b 100644
--- a/saleor/asgi/cors_handler.py
+++ b/saleor/asgi/cors_handler.py
@@ -5,6 +5,7 @@ from asgiref.typing import (
ASGI3Application,
ASGIReceiveCallable,
ASGISendCallable,
+ ASGISendEvent,
HTTPResponseBodyEvent,
HTTPResponseStartEvent,
HTTPScope,
@@ -18,7 +19,22 @@ def cors_handler(application: ASGI3Application) -> ASGI3Application:
scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
) -> None:
# handle CORS preflight requests
- if scope.get("type") == "http" and scope.get("method") == "OPTIONS":
+ if scope["type"] != "http":
+ await application(scope, receive, send)
+ return
+ # determine the origin of the request
+ request_origin: str = ""
+ for header, value in scope.get("headers", []):
+ if header == b"origin":
+ request_origin = value.decode("latin1")
+ # if the origin is allowed, add the appropriate CORS headers
+ origin_match = False
+ if request_origin:
+ for allowed_origin in settings.ALLOWED_GRAPHQL_ORIGINS:
+ if fnmatchcase(request_origin, allowed_origin):
+ origin_match = True
+ break
+ if scope["method"] == "OPTIONS":
scope = cast(HTTPScope, scope)
response_headers: list[Tuple[bytes, bytes]] = [
(b"access-control-allow-credentials", b"true"),
@@ -31,18 +47,6 @@ def cors_handler(application: ASGI3Application) -> ASGI3Application:
(b"access-control-max-age", b"600"),
(b"vary", b"Origin"),
]
- # determine the origin of the request
- request_origin: str = ""
- for header, value in scope.get("headers", []):
- if header == b"origin":
- request_origin = value.decode("latin1")
- # if the origin is allowed, add the appropriate CORS headers
- origin_match = False
- if request_origin:
- for allowed_origin in settings.ALLOWED_GRAPHQL_ORIGINS:
- if fnmatchcase(request_origin, allowed_origin):
- origin_match = True
- break
if origin_match:
response_headers.append(
(
@@ -64,6 +68,39 @@ def cors_handler(application: ASGI3Application) -> ASGI3Application:
)
)
else:
- await application(scope, receive, send)
+
+ async def send_with_origin(message: ASGISendEvent) -> None:
+ if message["type"] == "http.response.start":
+ response_headers = [
+ (key, value)
+ for key, value in message["headers"]
+ if key.lower() not in {b"access-control-allow-origin", b"vary"}
+ ]
+ vary_header = next(
+ (
+ value
+ for key, value in message["headers"]
+ if key.lower() == b"vary"
+ ),
+ b"",
+ )
+ if origin_match:
+ response_headers.append(
+ (
+ b"access-control-allow-origin",
+ request_origin.encode("latin1"),
+ )
+ )
+ if b"Origin" not in vary_header:
+ if vary_header:
+ vary_header += b", Origin"
+ else:
+ vary_header = b"Origin"
+ if vary_header:
+ response_headers.append((b"vary", vary_header))
+ message["headers"] = sorted(response_headers)
+ await send(message)
+
+ await application(scope, receive, send_with_origin)
return cors_wrapper
diff --git a/saleor/asgi/tests/test_cors.py b/saleor/asgi/tests/test_cors.py
index bbe0244198..8fb7012c27 100644
--- a/saleor/asgi/tests/test_cors.py
+++ b/saleor/asgi/tests/test_cors.py
@@ -17,12 +17,12 @@ ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"
ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"
-def build_scope(origin: str) -> HTTPScope:
+def build_scope(origin: str, method: str) -> HTTPScope:
return {
"type": "http",
"asgi": {"spec_version": "2.1", "version": "3.0"},
"http_version": "2",
- "method": "OPTIONS",
+ "method": method,
"scheme": "https",
"path": "/",
"raw_path": b"/",
@@ -51,10 +51,10 @@ async def run_app(app: ASGI3Application, scope: HTTPScope) -> List[dict]:
return events
-async def test_access_control_header(asgi_app: ASGI3Application, settings):
+async def test_access_control_header_preflight(asgi_app: ASGI3Application, settings):
settings.ALLOWED_GRAPHQL_ORIGINS = ["*"]
cors_app = cors_handler(asgi_app)
- events = await run_app(cors_app, build_scope("http://localhost:3000"))
+ events = await run_app(cors_app, build_scope("http://localhost:3000", "OPTIONS"))
assert events == [
HTTPResponseStartEvent(
type="http.response.start",
@@ -77,6 +77,25 @@ async def test_access_control_header(asgi_app: ASGI3Application, settings):
]
+async def test_access_control_header_simple(asgi_app: ASGI3Application, settings):
+ settings.ALLOWED_GRAPHQL_ORIGINS = ["*"]
+ cors_app = cors_handler(asgi_app)
+ events = await run_app(cors_app, build_scope("http://localhost:3000", "POST"))
+ assert events == [
+ HTTPResponseStartEvent(
+ type="http.response.start",
+ status=200,
+ headers=[
+ (b"access-control-allow-origin", b"http://localhost:3000"),
+ (b"content-type", b"text/plain"),
+ (b"vary", b"Origin"),
+ ],
+ trailers=False,
+ ),
+ HTTPResponseBodyEvent(type="http.response.body", body=b"", more_body=False),
+ ]
+
+
@pytest.mark.parametrize(
"allowed_origins,origin",
[
@@ -96,7 +115,7 @@ async def test_access_control_allowed_origins(
):
settings.ALLOWED_GRAPHQL_ORIGINS = allowed_origins
cors_app = cors_handler(asgi_app)
- events = await run_app(cors_app, build_scope(origin))
+ events = await run_app(cors_app, build_scope(origin, "OPTIONS"))
assert events[0]["type"] == "http.response.start"
assert events[0]["status"] == 200
assert (b"access-control-allow-origin", origin.encode("latin1")) in events[0][
@@ -120,7 +139,7 @@ async def test_access_control_disallowed_origins(
):
settings.ALLOWED_GRAPHQL_ORIGINS = allowed_origins
cors_app = cors_handler(asgi_app)
- events = await run_app(cors_app, build_scope(origin))
+ events = await run_app(cors_app, build_scope(origin, "OPTIONS"))
assert events[0]["type"] == "http.response.start"
assert events[0]["status"] == 400
assert (b"access-control-allow-origin", origin.encode("latin1")) not in events[0][
diff --git a/saleor/settings.py b/saleor/settings.py
index 62e22910ce..9fde2eb21c 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -437,7 +437,9 @@ TEST_RUNNER = "saleor.tests.runner.PytestTestRunner"
PLAYGROUND_ENABLED = get_bool_from_env("PLAYGROUND_ENABLED", True)
ALLOWED_HOSTS = get_list(os.environ.get("ALLOWED_HOSTS", "localhost,127.0.0.1"))
-ALLOWED_GRAPHQL_ORIGINS = get_list(os.environ.get("ALLOWED_GRAPHQL_ORIGINS", "*"))
+ALLOWED_GRAPHQL_ORIGINS: List[str] = get_list(
+ os.environ.get("ALLOWED_GRAPHQL_ORIGINS", "*")
+)
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")