prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Bug: CORS Middleware not setting all headers as per spec
  ### Description
  
  Right now, there's only a handful of headers that are only being set for the preflight request. They must be set for both the preflight and actual request. 
  https://fetch.spec.whatwg.org/#http-responses
  
  Only `Access-Control-Allow-Origin` is being set here.
  https://github.com/litestar-org/litestar/blob/1fb981da4b6171cd3fa348c9ffe1c575c5bc862f/litestar/middleware/cors.py#L61-L73
  
  Only `Access-Control-Allow-Credentials` and `Access-Control-Expose-Headers` get set here, and this is what the above code uses to update headers
  https://github.com/litestar-org/litestar/blob/1fb981da4b6171cd3fa348c9ffe1c575c5bc862f/litestar/config/cors.py#L123-L136
  
  This still doesn't account for:
  - Access-Control-Allow-Methods
  - Access-Control-Allow-Headers
  
  which are only set on preflight, but should also be set to the actual request.
  
  ### Litestar Version
  
  2.2.1
  
  ### Platform
  
  - [X] Linux
  - [ ] Mac
  - [ ] Windows
  - [ ] Other (Please specify in the description above)
  
  <!-- POLAR PLEDGE BADGE START -->
  ---
  > [!NOTE]  
  > While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and 
  > [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
  >
  > Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
  > * 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.
  
  <a href="https://polar.sh/litestar-org/litestar/issues/3178">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/3178/pledge.svg?darkmode=1">
    <img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/3178/pledge.svg">
  </picture>
  </a>
  <!-- POLAR PLEDGE BADGE END -->
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `litestar/middleware/cors.py`
  Content:
  ```
  1 from __future__ import annotations
  2 
  3 from typing import TYPE_CHECKING
  4 
  5 from litestar.datastructures import Headers, MutableScopeHeaders
  6 from litestar.enums import ScopeType
  7 from litestar.middleware.base import AbstractMiddleware
  8 
  9 __all__ = ("CORSMiddleware",)
  10 
  11 
  12 if TYPE_CHECKING:
  13     from litestar.config.cors import CORSConfig
  14     from litestar.types import ASGIApp, Message, Receive, Scope, Send
  15 
  16 
  17 class CORSMiddleware(AbstractMiddleware):
  18     """CORS Middleware."""
  19 
  20     __slots__ = ("config",)
  21 
  22     def __init__(self, app: ASGIApp, config: CORSConfig) -> None:
  23         """Middleware that adds CORS validation to the application.
  24 
  25         Args:
  26             app: The ``next`` ASGI app to call.
  27             config: An instance of :class:`CORSConfig <litestar.config.cors.CORSConfig>`
  28         """
  29         super().__init__(app=app, scopes={ScopeType.HTTP})
  30         self.config = config
  31 
  32     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  33         """ASGI callable.
  34 
  35         Args:
  36             scope: The ASGI connection scope.
  37             receive: The ASGI receive function.
  38             send: The ASGI send function.
  39 
  40         Returns:
  41             None
  42         """
  43         headers = Headers.from_scope(scope=scope)
  44         if origin := headers.get("origin"):
  45             await self.app(scope, receive, self.send_wrapper(send=send, origin=origin, has_cookie="cookie" in headers))
  46         else:
  47             await self.app(scope, receive, send)
  48 
  49     def send_wrapper(self, send: Send, origin: str, has_cookie: bool) -> Send:
  50         """Wrap ``send`` to ensure that state is not disconnected.
  51 
  52         Args:
  53             has_cookie: Boolean flag dictating if the connection has a cookie set.
  54             origin: The value of the ``Origin`` header.
  55             send: The ASGI send function.
  56 
  57         Returns:
  58             An ASGI send function.
  59         """
  60 
  61         async def wrapped_send(message: Message) -> None:
  62             if message["type"] == "http.response.start":
  63                 message.setdefault("headers", [])
  64                 headers = MutableScopeHeaders.from_message(message=message)
  65                 headers.update(self.config.simple_headers)
  66 
  67                 if (self.config.is_allow_all_origins and has_cookie) or (
  68                     not self.config.is_allow_all_origins and self.config.is_origin_allowed(origin=origin)
  69                 ):
  70                     headers["Access-Control-Allow-Origin"] = origin
  71                     headers["Vary"] = "Origin"
  72 
  73             await send(message)
  74 
  75         return wrapped_send
  76
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/litestar/middleware/cors.py b/litestar/middleware/cors.py
  --- a/litestar/middleware/cors.py
  +++ b/litestar/middleware/cors.py
  @@ -70,6 +70,15 @@
                       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
  
verification_info: {"golden_diff": "diff --git a/litestar/middleware/cors.py b/litestar/middleware/cors.py\n--- a/litestar/middleware/cors.py\n+++ b/litestar/middleware/cors.py\n@@ -70,6 +70,15 @@\n                     headers[\"Access-Control-Allow-Origin\"] = origin\n                     headers[\"Vary\"] = \"Origin\"\n \n+                # We don't want to overwrite this for preflight requests.\n+                allow_headers = headers.get(\"Access-Control-Allow-Headers\")\n+                if not allow_headers and self.config.allow_headers:\n+                    headers[\"Access-Control-Allow-Headers\"] = \", \".join(sorted(set(self.config.allow_headers)))\n+\n+                allow_methods = headers.get(\"Access-Control-Allow-Methods\")\n+                if not allow_methods and self.config.allow_methods:\n+                    headers[\"Access-Control-Allow-Methods\"] = \", \".join(sorted(set(self.config.allow_methods)))\n+\n             await send(message)\n \n         return wrapped_send\n", "issue": "Bug: CORS Middleware not setting all headers as per spec\n### Description\r\n\r\nRight now, there's only a handful of headers that are only being set for the preflight request. They must be set for both the preflight and actual request. \r\nhttps://fetch.spec.whatwg.org/#http-responses\r\n\r\nOnly `Access-Control-Allow-Origin` is being set here.\r\nhttps://github.com/litestar-org/litestar/blob/1fb981da4b6171cd3fa348c9ffe1c575c5bc862f/litestar/middleware/cors.py#L61-L73\r\n\r\nOnly `Access-Control-Allow-Credentials` and `Access-Control-Expose-Headers` get set here, and this is what the above code uses to update headers\r\nhttps://github.com/litestar-org/litestar/blob/1fb981da4b6171cd3fa348c9ffe1c575c5bc862f/litestar/config/cors.py#L123-L136\r\n\r\nThis still doesn't account for:\r\n- Access-Control-Allow-Methods\r\n- Access-Control-Allow-Headers\r\n\r\nwhich are only set on preflight, but should also be set to the actual request.\r\n\r\n### Litestar Version\r\n\r\n2.2.1\r\n\r\n### Platform\r\n\r\n- [X] Linux\r\n- [ ] Mac\r\n- [ ] Windows\r\n- [ ] Other (Please specify in the description above)\r\n\r\n<!-- POLAR PLEDGE BADGE START -->\r\n---\r\n> [!NOTE]  \r\n> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and \r\n> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.\r\n>\r\n> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)\r\n> * If you would like to see an issue prioritized, make a pledge towards it!\r\n> * We receive the pledge once the issue is completed & verified\r\n> * This, along with engagement in the community, helps us know which features are a priority to our users.\r\n\r\n<a href=\"https://polar.sh/litestar-org/litestar/issues/3178\">\r\n<picture>\r\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://polar.sh/api/github/litestar-org/litestar/issues/3178/pledge.svg?darkmode=1\">\r\n  <img alt=\"Fund with Polar\" src=\"https://polar.sh/api/github/litestar-org/litestar/issues/3178/pledge.svg\">\r\n</picture>\r\n</a>\r\n<!-- POLAR PLEDGE BADGE END -->\r\n\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom litestar.datastructures import Headers, MutableScopeHeaders\nfrom litestar.enums import ScopeType\nfrom litestar.middleware.base import AbstractMiddleware\n\n__all__ = (\"CORSMiddleware\",)\n\n\nif TYPE_CHECKING:\n    from litestar.config.cors import CORSConfig\n    from litestar.types import ASGIApp, Message, Receive, Scope, Send\n\n\nclass CORSMiddleware(AbstractMiddleware):\n    \"\"\"CORS Middleware.\"\"\"\n\n    __slots__ = (\"config\",)\n\n    def __init__(self, app: ASGIApp, config: CORSConfig) -> None:\n        \"\"\"Middleware that adds CORS validation to the application.\n\n        Args:\n            app: The ``next`` ASGI app to call.\n            config: An instance of :class:`CORSConfig <litestar.config.cors.CORSConfig>`\n        \"\"\"\n        super().__init__(app=app, scopes={ScopeType.HTTP})\n        self.config = config\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        \"\"\"ASGI callable.\n\n        Args:\n            scope: The ASGI connection scope.\n            receive: The ASGI receive function.\n            send: The ASGI send function.\n\n        Returns:\n            None\n        \"\"\"\n        headers = Headers.from_scope(scope=scope)\n        if origin := headers.get(\"origin\"):\n            await self.app(scope, receive, self.send_wrapper(send=send, origin=origin, has_cookie=\"cookie\" in headers))\n        else:\n            await self.app(scope, receive, send)\n\n    def send_wrapper(self, send: Send, origin: str, has_cookie: bool) -> Send:\n        \"\"\"Wrap ``send`` to ensure that state is not disconnected.\n\n        Args:\n            has_cookie: Boolean flag dictating if the connection has a cookie set.\n            origin: The value of the ``Origin`` header.\n            send: The ASGI send function.\n\n        Returns:\n            An ASGI send function.\n        \"\"\"\n\n        async def wrapped_send(message: Message) -> None:\n            if message[\"type\"] == \"http.response.start\":\n                message.setdefault(\"headers\", [])\n                headers = MutableScopeHeaders.from_message(message=message)\n                headers.update(self.config.simple_headers)\n\n                if (self.config.is_allow_all_origins and has_cookie) or (\n                    not self.config.is_allow_all_origins and self.config.is_origin_allowed(origin=origin)\n                ):\n                    headers[\"Access-Control-Allow-Origin\"] = origin\n                    headers[\"Vary\"] = \"Origin\"\n\n            await send(message)\n\n        return wrapped_send\n", "path": "litestar/middleware/cors.py"}], "after_files": [{"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom litestar.datastructures import Headers, MutableScopeHeaders\nfrom litestar.enums import ScopeType\nfrom litestar.middleware.base import AbstractMiddleware\n\n__all__ = (\"CORSMiddleware\",)\n\n\nif TYPE_CHECKING:\n    from litestar.config.cors import CORSConfig\n    from litestar.types import ASGIApp, Message, Receive, Scope, Send\n\n\nclass CORSMiddleware(AbstractMiddleware):\n    \"\"\"CORS Middleware.\"\"\"\n\n    __slots__ = (\"config\",)\n\n    def __init__(self, app: ASGIApp, config: CORSConfig) -> None:\n        \"\"\"Middleware that adds CORS validation to the application.\n\n        Args:\n            app: The ``next`` ASGI app to call.\n            config: An instance of :class:`CORSConfig <litestar.config.cors.CORSConfig>`\n        \"\"\"\n        super().__init__(app=app, scopes={ScopeType.HTTP})\n        self.config = config\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        \"\"\"ASGI callable.\n\n        Args:\n            scope: The ASGI connection scope.\n            receive: The ASGI receive function.\n            send: The ASGI send function.\n\n        Returns:\n            None\n        \"\"\"\n        headers = Headers.from_scope(scope=scope)\n        if origin := headers.get(\"origin\"):\n            await self.app(scope, receive, self.send_wrapper(send=send, origin=origin, has_cookie=\"cookie\" in headers))\n        else:\n            await self.app(scope, receive, send)\n\n    def send_wrapper(self, send: Send, origin: str, has_cookie: bool) -> Send:\n        \"\"\"Wrap ``send`` to ensure that state is not disconnected.\n\n        Args:\n            has_cookie: Boolean flag dictating if the connection has a cookie set.\n            origin: The value of the ``Origin`` header.\n            send: The ASGI send function.\n\n        Returns:\n            An ASGI send function.\n        \"\"\"\n\n        async def wrapped_send(message: Message) -> None:\n            if message[\"type\"] == \"http.response.start\":\n                message.setdefault(\"headers\", [])\n                headers = MutableScopeHeaders.from_message(message=message)\n                headers.update(self.config.simple_headers)\n\n                if (self.config.is_allow_all_origins and has_cookie) or (\n                    not self.config.is_allow_all_origins and self.config.is_origin_allowed(origin=origin)\n                ):\n                    headers[\"Access-Control-Allow-Origin\"] = origin\n                    headers[\"Vary\"] = \"Origin\"\n\n                # We don't want to overwrite this for preflight requests.\n                allow_headers = headers.get(\"Access-Control-Allow-Headers\")\n                if not allow_headers and self.config.allow_headers:\n                    headers[\"Access-Control-Allow-Headers\"] = \", \".join(sorted(set(self.config.allow_headers)))\n\n                allow_methods = headers.get(\"Access-Control-Allow-Methods\")\n                if not allow_methods and self.config.allow_methods:\n                    headers[\"Access-Control-Allow-Methods\"] = \", \".join(sorted(set(self.config.allow_methods)))\n\n            await send(message)\n\n        return wrapped_send\n", "path": "litestar/middleware/cors.py"}]}