litestar-org / litestar

Production-ready, Light, Flexible and Extensible ASGI API framework | Effortlessly Build Performant APIs
https://litestar.dev/
MIT License
5.65k stars 384 forks source link

bug: CORS middleware not working with mounted applications #3402

Closed byte-bot-app[bot] closed 7 months ago

byte-bot-app[bot] commented 7 months ago

Reported by

peter in Discord: CORS middleware not working with mounted applications

Description

CORS pre-flight requests are passed to the mounted application, and not handled by the framework's CORS implementation.

MCVE

from http import HTTPStatus

import uvicorn
from litestar import Litestar, get, Response, asgi
from litestar.config.cors import CORSConfig

@get("/route")
async def route() -> Response[str]:
    return Response(content="Content", status_code=HTTPStatus.METHOD_NOT_ALLOWED)

cors_config = CORSConfig(allow_methods=["*"], allow_origins=["https://some-domain.com"])
app = Litestar(
    cors_config=cors_config,
    route_handlers=[
        asgi("/app", is_mount=True)(Litestar()),
        route,
    ]
)

if __name__ == "__main__":
    uvicorn.run("main:app", reload=True)
import httpx

for path in ["/app", "/route"]:
    response = httpx.options(
        f"http://127.0.0.1:8000{path}",
        headers={"origin": "https://some-domain.com"},
    )
    print(response.status_code)
    print(response.content)
    print(response.headers)

Logs

           /^\/^\
         _|__|  O|
\/     /~     \_/ \
 \____|__________/  \
        \_______      \
                `\     \                 \
                  |     |                  \
                 /      /                    \
                /     /                       \\
              /      /                         \ \
             /     /                            \  \
           /     /             _----_            \   \
          /     /           _-~      ~-_         |   |
         (      (        _-~    _--_    ~-_     _/   |
          \      ~-____-~    _-~    ~-_    ~-_-~    /
            ~-_           _-~          ~-_       _-~
               ~--______-~                ~-___-~

Litestar Version

2.8.2


[!NOTE]
While we are open for sponsoring on GitHub Sponsors and OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.

Check out all issues funded or available for funding on our Polar.sh dashboard

  • If you would like to see an issue prioritized, make a pledge towards it!
  • We receive the pledge once the issue is completed & verified
  • This, along with engagement in the community, helps us know which features are a priority to our users.

Fund with Polar

github-actions[bot] commented 7 months ago

This issue has been closed in #3401. The change will be included in the upcoming patch release.