We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Credentialed CORS standard requests should not respond with wildcard origins
See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Credentialed_requests_and_wildcards 

If a standard request is made, that includes any cookie headers, then CORSMiddleware *ought* to strictly respond with the requested origin, rather than a wildcard.

This is actually potentially a bit fiddly since we maybe also need to make sure to *set or add* Vary: Origin in those cases, in order to ensure correct cacheability.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `starlette/middleware/cors.py`
Content:
```
1 from starlette.datastructures import Headers, MutableHeaders, URL
2 from starlette.responses import PlainTextResponse
3 from starlette.types import ASGIApp, ASGIInstance, Scope
4 import functools
5 import typing
6 import re
7 
8 
9 ALL_METHODS = ("DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT")
10 
11 
12 class CORSMiddleware:
13     def __init__(
14         self,
15         app: ASGIApp,
16         allow_origins: typing.Sequence[str] = (),
17         allow_methods: typing.Sequence[str] = ("GET",),
18         allow_headers: typing.Sequence[str] = (),
19         allow_credentials: bool = False,
20         allow_origin_regex: str = None,
21         expose_headers: typing.Sequence[str] = (),
22         max_age: int = 600,
23     ) -> None:
24 
25         if "*" in allow_methods:
26             allow_methods = ALL_METHODS
27 
28         compiled_allow_origin_regex = None
29         if allow_origin_regex is not None:
30             compiled_allow_origin_regex = re.compile(allow_origin_regex)
31 
32         simple_headers = {}
33         if "*" in allow_origins:
34             simple_headers["Access-Control-Allow-Origin"] = "*"
35         if allow_credentials:
36             simple_headers["Access-Control-Allow-Credentials"] = "true"
37         if expose_headers:
38             simple_headers["Access-Control-Expose-Headers"] = ", ".join(expose_headers)
39 
40         preflight_headers = {}
41         if "*" in allow_origins:
42             preflight_headers["Access-Control-Allow-Origin"] = "*"
43         else:
44             preflight_headers["Vary"] = "Origin"
45         preflight_headers.update(
46             {
47                 "Access-Control-Allow-Methods": ", ".join(allow_methods),
48                 "Access-Control-Max-Age": str(max_age),
49             }
50         )
51         if allow_headers and "*" not in allow_headers:
52             preflight_headers["Access-Control-Allow-Headers"] = ", ".join(allow_headers)
53         if allow_credentials:
54             preflight_headers["Access-Control-Allow-Credentials"] = "true"
55 
56         self.app = app
57         self.allow_origins = allow_origins
58         self.allow_methods = allow_methods
59         self.allow_headers = allow_headers
60         self.allow_all_origins = "*" in allow_origins
61         self.allow_all_headers = "*" in allow_headers
62         self.allow_origin_regex = compiled_allow_origin_regex
63         self.simple_headers = simple_headers
64         self.preflight_headers = preflight_headers
65 
66     def __call__(self, scope: Scope):
67         if scope["type"] == "http":
68             method = scope["method"]
69             headers = Headers(scope["headers"])
70             origin = headers.get("origin")
71 
72             if origin is not None:
73                 if method == "OPTIONS" and "access-control-request-method" in headers:
74                     return self.preflight_response(request_headers=headers)
75                 else:
76                     return functools.partial(
77                         self.simple_response, scope=scope, origin=origin
78                     )
79 
80         return self.app(scope)
81 
82     def is_allowed_origin(self, origin):
83         if self.allow_all_origins:
84             return True
85 
86         if self.allow_origin_regex is not None and self.allow_origin_regex.match(
87             origin
88         ):
89             return True
90 
91         return origin in self.allow_origins
92 
93     def preflight_response(self, request_headers):
94         requested_origin = request_headers["origin"]
95         requested_method = request_headers["access-control-request-method"]
96         requested_headers = request_headers.get("access-control-request-headers")
97         requested_cookie = "cookie" in request_headers
98 
99         headers = dict(self.preflight_headers)
100         failures = []
101 
102         if self.is_allowed_origin(origin=requested_origin):
103             if not self.allow_all_origins:
104                 # If self.allow_all_origins is True, then the "Access-Control-Allow-Origin"
105                 # header is already set to "*".
106                 # If we only allow specific origins, then we have to mirror back
107                 # the Origin header in the response.
108                 headers["Access-Control-Allow-Origin"] = requested_origin
109         else:
110             failures.append("origin")
111 
112         if requested_method not in self.allow_methods:
113             failures.append("method")
114 
115         # If we allow all headers, then we have to mirror back any requested
116         # headers in the response.
117         if self.allow_all_headers and requested_headers is not None:
118             headers["Access-Control-Allow-Headers"] = requested_headers
119         elif requested_headers is not None:
120             for header in requested_headers.split(","):
121                 if header.strip() not in self.allow_headers:
122                     failures.append("headers")
123 
124         # We don't strictly need to use 400 responses here, since its up to
125         # the browser to enforce the CORS policy, but its more informative
126         # if we do.
127         if failures:
128             failure_text = "Disallowed CORS " + ", ".join(failures)
129             return PlainTextResponse(failure_text, status_code=400, headers=headers)
130 
131         return PlainTextResponse("OK", status_code=200, headers=headers)
132 
133     async def simple_response(self, receive, send, scope=None, origin=None):
134         inner = self.app(scope)
135         send = functools.partial(self.send, send=send, origin=origin)
136         await inner(receive, send)
137 
138     async def send(self, message, send=None, origin=None):
139         if message["type"] != "http.response.start":
140             await send(message)
141             return
142 
143         message.setdefault("headers", [])
144         headers = MutableHeaders(message["headers"])
145 
146         # If we only allow specific origins, then we have to mirror back
147         # the Origin header in the response.
148         if not self.allow_all_origins and self.is_allowed_origin(origin=origin):
149             headers["Access-Control-Allow-Origin"] = origin
150         headers.update(self.simple_headers)
151         await send(message)
152
```
--- 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()

```

diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py
--- a/starlette/middleware/cors.py
+++ b/starlette/middleware/cors.py
@@ -32,6 +32,8 @@
         simple_headers = {}
         if "*" in allow_origins:
             simple_headers["Access-Control-Allow-Origin"] = "*"
+        else:
+            simple_headers["Vary"] = "Origin"
         if allow_credentials:
             simple_headers["Access-Control-Allow-Credentials"] = "true"
         if expose_headers:
@@ -74,7 +76,7 @@
                     return self.preflight_response(request_headers=headers)
                 else:
                     return functools.partial(
-                        self.simple_response, scope=scope, origin=origin
+                        self.simple_response, scope=scope, request_headers=headers
                     )
 
         return self.app(scope)
@@ -130,22 +132,31 @@
 
         return PlainTextResponse("OK", status_code=200, headers=headers)
 
-    async def simple_response(self, receive, send, scope=None, origin=None):
+    async def simple_response(self, receive, send, scope=None, request_headers=None):
         inner = self.app(scope)
-        send = functools.partial(self.send, send=send, origin=origin)
+        send = functools.partial(self.send, send=send, request_headers=request_headers)
         await inner(receive, send)
 
-    async def send(self, message, send=None, origin=None):
+    async def send(self, message, send=None, request_headers=None):
         if message["type"] != "http.response.start":
             await send(message)
             return
 
         message.setdefault("headers", [])
         headers = MutableHeaders(message["headers"])
+        origin = request_headers["Origin"]
+        has_cookie = "cookie" in request_headers
+
+        # If request includes any cookie headers, then we must respond
+        # with the specific origin instead of '*'.
+        if self.allow_all_origins and has_cookie:
+            self.simple_headers["Access-Control-Allow-Origin"] = origin
 
         # If we only allow specific origins, then we have to mirror back
         # the Origin header in the response.
-        if not self.allow_all_origins and self.is_allowed_origin(origin=origin):
+        elif not self.allow_all_origins and self.is_allowed_origin(origin=origin):
             headers["Access-Control-Allow-Origin"] = origin
+            if "vary" in headers:
+                self.simple_headers["Vary"] = f"{headers.get('vary')}, Origin"
         headers.update(self.simple_headers)
         await send(message)

{"golden_diff": "diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py\n--- a/starlette/middleware/cors.py\n+++ b/starlette/middleware/cors.py\n@@ -32,6 +32,8 @@\n         simple_headers = {}\n         if \"*\" in allow_origins:\n             simple_headers[\"Access-Control-Allow-Origin\"] = \"*\"\n+        else:\n+            simple_headers[\"Vary\"] = \"Origin\"\n         if allow_credentials:\n             simple_headers[\"Access-Control-Allow-Credentials\"] = \"true\"\n         if expose_headers:\n@@ -74,7 +76,7 @@\n                     return self.preflight_response(request_headers=headers)\n                 else:\n                     return functools.partial(\n-                        self.simple_response, scope=scope, origin=origin\n+                        self.simple_response, scope=scope, request_headers=headers\n                     )\n \n         return self.app(scope)\n@@ -130,22 +132,31 @@\n \n         return PlainTextResponse(\"OK\", status_code=200, headers=headers)\n \n-    async def simple_response(self, receive, send, scope=None, origin=None):\n+    async def simple_response(self, receive, send, scope=None, request_headers=None):\n         inner = self.app(scope)\n-        send = functools.partial(self.send, send=send, origin=origin)\n+        send = functools.partial(self.send, send=send, request_headers=request_headers)\n         await inner(receive, send)\n \n-    async def send(self, message, send=None, origin=None):\n+    async def send(self, message, send=None, request_headers=None):\n         if message[\"type\"] != \"http.response.start\":\n             await send(message)\n             return\n \n         message.setdefault(\"headers\", [])\n         headers = MutableHeaders(message[\"headers\"])\n+        origin = request_headers[\"Origin\"]\n+        has_cookie = \"cookie\" in request_headers\n+\n+        # If request includes any cookie headers, then we must respond\n+        # with the specific origin instead of '*'.\n+        if self.allow_all_origins and has_cookie:\n+            self.simple_headers[\"Access-Control-Allow-Origin\"] = origin\n \n         # If we only allow specific origins, then we have to mirror back\n         # the Origin header in the response.\n-        if not self.allow_all_origins and self.is_allowed_origin(origin=origin):\n+        elif not self.allow_all_origins and self.is_allowed_origin(origin=origin):\n             headers[\"Access-Control-Allow-Origin\"] = origin\n+            if \"vary\" in headers:\n+                self.simple_headers[\"Vary\"] = f\"{headers.get('vary')}, Origin\"\n         headers.update(self.simple_headers)\n         await send(message)\n", "issue": "Credentialed CORS standard requests should not respond with wildcard origins\nSee https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Credentialed_requests_and_wildcards \r\n\r\nIf a standard request is made, that includes any cookie headers, then CORSMiddleware *ought* to strictly respond with the requested origin, rather than a wildcard.\r\n\r\nThis is actually potentially a bit fiddly since we maybe also need to make sure to *set or add* Vary: Origin in those cases, in order to ensure correct cacheability.\n", "before_files": [{"content": "from starlette.datastructures import Headers, MutableHeaders, URL\nfrom starlette.responses import PlainTextResponse\nfrom starlette.types import ASGIApp, ASGIInstance, Scope\nimport functools\nimport typing\nimport re\n\n\nALL_METHODS = (\"DELETE\", \"GET\", \"OPTIONS\", \"PATCH\", \"POST\", \"PUT\")\n\n\nclass CORSMiddleware:\n    def __init__(\n        self,\n        app: ASGIApp,\n        allow_origins: typing.Sequence[str] = (),\n        allow_methods: typing.Sequence[str] = (\"GET\",),\n        allow_headers: typing.Sequence[str] = (),\n        allow_credentials: bool = False,\n        allow_origin_regex: str = None,\n        expose_headers: typing.Sequence[str] = (),\n        max_age: int = 600,\n    ) -> None:\n\n        if \"*\" in allow_methods:\n            allow_methods = ALL_METHODS\n\n        compiled_allow_origin_regex = None\n        if allow_origin_regex is not None:\n            compiled_allow_origin_regex = re.compile(allow_origin_regex)\n\n        simple_headers = {}\n        if \"*\" in allow_origins:\n            simple_headers[\"Access-Control-Allow-Origin\"] = \"*\"\n        if allow_credentials:\n            simple_headers[\"Access-Control-Allow-Credentials\"] = \"true\"\n        if expose_headers:\n            simple_headers[\"Access-Control-Expose-Headers\"] = \", \".join(expose_headers)\n\n        preflight_headers = {}\n        if \"*\" in allow_origins:\n            preflight_headers[\"Access-Control-Allow-Origin\"] = \"*\"\n        else:\n            preflight_headers[\"Vary\"] = \"Origin\"\n        preflight_headers.update(\n            {\n                \"Access-Control-Allow-Methods\": \", \".join(allow_methods),\n                \"Access-Control-Max-Age\": str(max_age),\n            }\n        )\n        if allow_headers and \"*\" not in allow_headers:\n            preflight_headers[\"Access-Control-Allow-Headers\"] = \", \".join(allow_headers)\n        if allow_credentials:\n            preflight_headers[\"Access-Control-Allow-Credentials\"] = \"true\"\n\n        self.app = app\n        self.allow_origins = allow_origins\n        self.allow_methods = allow_methods\n        self.allow_headers = allow_headers\n        self.allow_all_origins = \"*\" in allow_origins\n        self.allow_all_headers = \"*\" in allow_headers\n        self.allow_origin_regex = compiled_allow_origin_regex\n        self.simple_headers = simple_headers\n        self.preflight_headers = preflight_headers\n\n    def __call__(self, scope: Scope):\n        if scope[\"type\"] == \"http\":\n            method = scope[\"method\"]\n            headers = Headers(scope[\"headers\"])\n            origin = headers.get(\"origin\")\n\n            if origin is not None:\n                if method == \"OPTIONS\" and \"access-control-request-method\" in headers:\n                    return self.preflight_response(request_headers=headers)\n                else:\n                    return functools.partial(\n                        self.simple_response, scope=scope, origin=origin\n                    )\n\n        return self.app(scope)\n\n    def is_allowed_origin(self, origin):\n        if self.allow_all_origins:\n            return True\n\n        if self.allow_origin_regex is not None and self.allow_origin_regex.match(\n            origin\n        ):\n            return True\n\n        return origin in self.allow_origins\n\n    def preflight_response(self, request_headers):\n        requested_origin = request_headers[\"origin\"]\n        requested_method = request_headers[\"access-control-request-method\"]\n        requested_headers = request_headers.get(\"access-control-request-headers\")\n        requested_cookie = \"cookie\" in request_headers\n\n        headers = dict(self.preflight_headers)\n        failures = []\n\n        if self.is_allowed_origin(origin=requested_origin):\n            if not self.allow_all_origins:\n                # If self.allow_all_origins is True, then the \"Access-Control-Allow-Origin\"\n                # header is already set to \"*\".\n                # If we only allow specific origins, then we have to mirror back\n                # the Origin header in the response.\n                headers[\"Access-Control-Allow-Origin\"] = requested_origin\n        else:\n            failures.append(\"origin\")\n\n        if requested_method not in self.allow_methods:\n            failures.append(\"method\")\n\n        # If we allow all headers, then we have to mirror back any requested\n        # headers in the response.\n        if self.allow_all_headers and requested_headers is not None:\n            headers[\"Access-Control-Allow-Headers\"] = requested_headers\n        elif requested_headers is not None:\n            for header in requested_headers.split(\",\"):\n                if header.strip() not in self.allow_headers:\n                    failures.append(\"headers\")\n\n        # We don't strictly need to use 400 responses here, since its up to\n        # the browser to enforce the CORS policy, but its more informative\n        # if we do.\n        if failures:\n            failure_text = \"Disallowed CORS \" + \", \".join(failures)\n            return PlainTextResponse(failure_text, status_code=400, headers=headers)\n\n        return PlainTextResponse(\"OK\", status_code=200, headers=headers)\n\n    async def simple_response(self, receive, send, scope=None, origin=None):\n        inner = self.app(scope)\n        send = functools.partial(self.send, send=send, origin=origin)\n        await inner(receive, send)\n\n    async def send(self, message, send=None, origin=None):\n        if message[\"type\"] != \"http.response.start\":\n            await send(message)\n            return\n\n        message.setdefault(\"headers\", [])\n        headers = MutableHeaders(message[\"headers\"])\n\n        # If we only allow specific origins, then we have to mirror back\n        # the Origin header in the response.\n        if not self.allow_all_origins and self.is_allowed_origin(origin=origin):\n            headers[\"Access-Control-Allow-Origin\"] = origin\n        headers.update(self.simple_headers)\n        await send(message)\n", "path": "starlette/middleware/cors.py"}], "after_files": [{"content": "from starlette.datastructures import Headers, MutableHeaders, URL\nfrom starlette.responses import PlainTextResponse\nfrom starlette.types import ASGIApp, ASGIInstance, Scope\nimport functools\nimport typing\nimport re\n\n\nALL_METHODS = (\"DELETE\", \"GET\", \"OPTIONS\", \"PATCH\", \"POST\", \"PUT\")\n\n\nclass CORSMiddleware:\n    def __init__(\n        self,\n        app: ASGIApp,\n        allow_origins: typing.Sequence[str] = (),\n        allow_methods: typing.Sequence[str] = (\"GET\",),\n        allow_headers: typing.Sequence[str] = (),\n        allow_credentials: bool = False,\n        allow_origin_regex: str = None,\n        expose_headers: typing.Sequence[str] = (),\n        max_age: int = 600,\n    ) -> None:\n\n        if \"*\" in allow_methods:\n            allow_methods = ALL_METHODS\n\n        compiled_allow_origin_regex = None\n        if allow_origin_regex is not None:\n            compiled_allow_origin_regex = re.compile(allow_origin_regex)\n\n        simple_headers = {}\n        if \"*\" in allow_origins:\n            simple_headers[\"Access-Control-Allow-Origin\"] = \"*\"\n        else:\n            simple_headers[\"Vary\"] = \"Origin\"\n        if allow_credentials:\n            simple_headers[\"Access-Control-Allow-Credentials\"] = \"true\"\n        if expose_headers:\n            simple_headers[\"Access-Control-Expose-Headers\"] = \", \".join(expose_headers)\n\n        preflight_headers = {}\n        if \"*\" in allow_origins:\n            preflight_headers[\"Access-Control-Allow-Origin\"] = \"*\"\n        else:\n            preflight_headers[\"Vary\"] = \"Origin\"\n        preflight_headers.update(\n            {\n                \"Access-Control-Allow-Methods\": \", \".join(allow_methods),\n                \"Access-Control-Max-Age\": str(max_age),\n            }\n        )\n        if allow_headers and \"*\" not in allow_headers:\n            preflight_headers[\"Access-Control-Allow-Headers\"] = \", \".join(allow_headers)\n        if allow_credentials:\n            preflight_headers[\"Access-Control-Allow-Credentials\"] = \"true\"\n\n        self.app = app\n        self.allow_origins = allow_origins\n        self.allow_methods = allow_methods\n        self.allow_headers = allow_headers\n        self.allow_all_origins = \"*\" in allow_origins\n        self.allow_all_headers = \"*\" in allow_headers\n        self.allow_origin_regex = compiled_allow_origin_regex\n        self.simple_headers = simple_headers\n        self.preflight_headers = preflight_headers\n\n    def __call__(self, scope: Scope):\n        if scope[\"type\"] == \"http\":\n            method = scope[\"method\"]\n            headers = Headers(scope[\"headers\"])\n            origin = headers.get(\"origin\")\n\n            if origin is not None:\n                if method == \"OPTIONS\" and \"access-control-request-method\" in headers:\n                    return self.preflight_response(request_headers=headers)\n                else:\n                    return functools.partial(\n                        self.simple_response, scope=scope, request_headers=headers\n                    )\n\n        return self.app(scope)\n\n    def is_allowed_origin(self, origin):\n        if self.allow_all_origins:\n            return True\n\n        if self.allow_origin_regex is not None and self.allow_origin_regex.match(\n            origin\n        ):\n            return True\n\n        return origin in self.allow_origins\n\n    def preflight_response(self, request_headers):\n        requested_origin = request_headers[\"origin\"]\n        requested_method = request_headers[\"access-control-request-method\"]\n        requested_headers = request_headers.get(\"access-control-request-headers\")\n        requested_cookie = \"cookie\" in request_headers\n\n        headers = dict(self.preflight_headers)\n        failures = []\n\n        if self.is_allowed_origin(origin=requested_origin):\n            if not self.allow_all_origins:\n                # If self.allow_all_origins is True, then the \"Access-Control-Allow-Origin\"\n                # header is already set to \"*\".\n                # If we only allow specific origins, then we have to mirror back\n                # the Origin header in the response.\n                headers[\"Access-Control-Allow-Origin\"] = requested_origin\n        else:\n            failures.append(\"origin\")\n\n        if requested_method not in self.allow_methods:\n            failures.append(\"method\")\n\n        # If we allow all headers, then we have to mirror back any requested\n        # headers in the response.\n        if self.allow_all_headers and requested_headers is not None:\n            headers[\"Access-Control-Allow-Headers\"] = requested_headers\n        elif requested_headers is not None:\n            for header in requested_headers.split(\",\"):\n                if header.strip() not in self.allow_headers:\n                    failures.append(\"headers\")\n\n        # We don't strictly need to use 400 responses here, since its up to\n        # the browser to enforce the CORS policy, but its more informative\n        # if we do.\n        if failures:\n            failure_text = \"Disallowed CORS \" + \", \".join(failures)\n            return PlainTextResponse(failure_text, status_code=400, headers=headers)\n\n        return PlainTextResponse(\"OK\", status_code=200, headers=headers)\n\n    async def simple_response(self, receive, send, scope=None, request_headers=None):\n        inner = self.app(scope)\n        send = functools.partial(self.send, send=send, request_headers=request_headers)\n        await inner(receive, send)\n\n    async def send(self, message, send=None, request_headers=None):\n        if message[\"type\"] != \"http.response.start\":\n            await send(message)\n            return\n\n        message.setdefault(\"headers\", [])\n        headers = MutableHeaders(message[\"headers\"])\n        origin = request_headers[\"Origin\"]\n        has_cookie = \"cookie\" in request_headers\n\n        # If request includes any cookie headers, then we must respond\n        # with the specific origin instead of '*'.\n        if self.allow_all_origins and has_cookie:\n            self.simple_headers[\"Access-Control-Allow-Origin\"] = origin\n\n        # If we only allow specific origins, then we have to mirror back\n        # the Origin header in the response.\n        elif not self.allow_all_origins and self.is_allowed_origin(origin=origin):\n            headers[\"Access-Control-Allow-Origin\"] = origin\n            if \"vary\" in headers:\n                self.simple_headers[\"Vary\"] = f\"{headers.get('vary')}, Origin\"\n        headers.update(self.simple_headers)\n        await send(message)\n", "path": "starlette/middleware/cors.py"}]}