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

fix: missing cors headers in response #3179

Merged
merged 5 commits into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions litestar/middleware/cors.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ async def wrapped_send(message: Message) -> None:
headers["Access-Control-Allow-Origin"] = origin
headers["Vary"] = "Origin"

# We don't want to overwrite this for preflight requests.
allow_headers = headers.get("Access-Control-Allow-Headers")
if not allow_headers and self.config.allow_headers:
headers["Access-Control-Allow-Headers"] = ", ".join(sorted(set(self.config.allow_headers)))

allow_methods = headers.get("Access-Control-Allow-Methods")
if not allow_methods and self.config.allow_methods:
headers["Access-Control-Allow-Methods"] = ", ".join(sorted(set(self.config.allow_methods)))

await send(message)

return wrapped_send
36 changes: 32 additions & 4 deletions tests/unit/test_middleware/test_cors_middleware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Dict, List, Mapping, Optional, cast
from typing import Any, Dict, List, Literal, Mapping, Optional, Union, cast

import pytest

Expand All @@ -7,6 +7,7 @@
from litestar.middleware.cors import CORSMiddleware
from litestar.status_codes import HTTP_200_OK, HTTP_404_NOT_FOUND
from litestar.testing import create_test_client
from litestar.types.asgi_types import Method


def test_setting_cors_middleware() -> None:
Expand Down Expand Up @@ -38,16 +39,31 @@ def test_setting_cors_middleware() -> None:
@pytest.mark.parametrize("origin", [None, "http://www.example.com", "https://moishe.zuchmir.com"])
@pytest.mark.parametrize("allow_origins", ["*", "http://www.example.com", "https://moishe.zuchmir.com"])
@pytest.mark.parametrize("allow_credentials", [True, False])
@pytest.mark.parametrize("expose_headers", ["X-First-Header", "SomeOtherHeader", "X-Second-Header"])
@pytest.mark.parametrize(
"expose_headers", [["x-first-header", "x-second-header", "x-third-header"], ["*"], ["x-first-header"]]
)
@pytest.mark.parametrize(
"allow_headers", [["x-first-header", "x-second-header", "x-third-header"], ["*"], ["x-first-header"]]
)
@pytest.mark.parametrize("allow_methods", [["GET", "POST", "PUT", "DELETE"], ["GET", "POST"], ["GET"]])
def test_cors_simple_response(
origin: Optional[str], allow_origins: List[str], allow_credentials: bool, expose_headers: List[str]
origin: Optional[str],
allow_origins: List[str],
allow_credentials: bool,
expose_headers: List[str],
allow_headers: List[str],
allow_methods: List[Union[Literal["*"], "Method"]],
) -> None:
@get("/")
def handler() -> Dict[str, str]:
return {"hello": "world"}

cors_config = CORSConfig(
allow_origins=allow_origins, allow_credentials=allow_credentials, expose_headers=expose_headers
allow_origins=allow_origins,
allow_credentials=allow_credentials,
expose_headers=expose_headers,
allow_headers=allow_headers,
allow_methods=allow_methods,
)

with create_test_client(handler, cors_config=cors_config) as client:
Expand All @@ -58,6 +74,8 @@ def handler() -> Dict[str, str]:
assert cors_config.expose_headers == expose_headers
assert cors_config.allow_origins == allow_origins
assert cors_config.allow_credentials == allow_credentials
assert cors_config.allow_headers == allow_headers
assert cors_config.allow_methods == allow_methods

if origin:
if cors_config.is_allow_all_origins:
Expand All @@ -68,10 +86,20 @@ def handler() -> Dict[str, str]:
assert response.headers.get("Access-Control-Expose-Headers") == ", ".join(
sorted(set(cors_config.expose_headers))
)
if cors_config.allow_headers:
assert response.headers.get("Access-Control-Allow-Headers") == ", ".join(
sorted(set(cors_config.allow_headers))
)
if cors_config.allow_methods:
assert response.headers.get("Access-Control-Allow-Methods") == ", ".join(
sorted(set(cors_config.allow_methods))
)
else:
assert "Access-Control-Allow-Origin" not in response.headers
assert "Access-Control-Allow-Credentials" not in response.headers
assert "Access-Control-Expose-Headers" not in response.headers
assert "Access-Control-Allow-Headers" not in response.headers
assert "Access-Control-Allow-Methods" not in response.headers


@pytest.mark.parametrize("origin, should_apply_cors", (("http://www.example.com", True), (None, False)))
Expand Down
Loading