|
| 1 | +"""Copy of fastapi.middleware.cors, with """ |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import functools |
| 6 | +import os |
| 7 | +import re |
| 8 | +import typing |
| 9 | + |
| 10 | +from starlette.datastructures import Headers, MutableHeaders |
| 11 | +from starlette.responses import PlainTextResponse, Response |
| 12 | +from starlette.types import ASGIApp, Message, Receive, Scope, Send |
| 13 | + |
| 14 | +PRIVATE = os.getenv("FS_PROXY_PRIVATE", False) == "True" |
| 15 | +ALL_METHODS = ("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT") |
| 16 | +SAFELISTED_HEADERS = {"Accept", "Accept-Language", "Content-Language", "Content-Type"} |
| 17 | + |
| 18 | + |
| 19 | +class CORSMiddleware: |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + app: ASGIApp, |
| 23 | + allow_origins: typing.Sequence[str] = (), |
| 24 | + allow_methods: typing.Sequence[str] = ("GET",), |
| 25 | + allow_headers: typing.Sequence[str] = (), |
| 26 | + allow_credentials: bool = False, |
| 27 | + allow_origin_regex: str | None = None, |
| 28 | + expose_headers: typing.Sequence[str] = (), |
| 29 | + max_age: int = 600, |
| 30 | + ) -> None: |
| 31 | + if "*" in allow_methods: |
| 32 | + allow_methods = ALL_METHODS |
| 33 | + |
| 34 | + compiled_allow_origin_regex = None |
| 35 | + if allow_origin_regex is not None: |
| 36 | + compiled_allow_origin_regex = re.compile(allow_origin_regex) |
| 37 | + |
| 38 | + allow_all_origins = "*" in allow_origins |
| 39 | + allow_all_headers = "*" in allow_headers |
| 40 | + preflight_explicit_allow_origin = not allow_all_origins or allow_credentials |
| 41 | + |
| 42 | + simple_headers = {} |
| 43 | + if allow_all_origins: |
| 44 | + simple_headers["Access-Control-Allow-Origin"] = "*" |
| 45 | + if allow_credentials: |
| 46 | + simple_headers["Access-Control-Allow-Credentials"] = "true" |
| 47 | + if expose_headers: |
| 48 | + simple_headers["Access-Control-Expose-Headers"] = ", ".join(expose_headers) |
| 49 | + |
| 50 | + preflight_headers = {} |
| 51 | + if preflight_explicit_allow_origin: |
| 52 | + # The origin value will be set in preflight_response() if it is allowed. |
| 53 | + preflight_headers["Vary"] = "Origin" |
| 54 | + else: |
| 55 | + preflight_headers["Access-Control-Allow-Origin"] = "*" |
| 56 | + preflight_headers.update( |
| 57 | + { |
| 58 | + "Access-Control-Allow-Methods": ", ".join(allow_methods), |
| 59 | + "Access-Control-Max-Age": str(max_age), |
| 60 | + } |
| 61 | + ) |
| 62 | + allow_headers = sorted(SAFELISTED_HEADERS | set(allow_headers)) |
| 63 | + if allow_headers and not allow_all_headers: |
| 64 | + preflight_headers["Access-Control-Allow-Headers"] = ", ".join(allow_headers) |
| 65 | + if allow_credentials: |
| 66 | + preflight_headers["Access-Control-Allow-Credentials"] = "true" |
| 67 | + |
| 68 | + self.app = app |
| 69 | + self.allow_origins = allow_origins |
| 70 | + self.allow_methods = allow_methods |
| 71 | + self.allow_headers = [h.lower() for h in allow_headers] |
| 72 | + self.allow_all_origins = allow_all_origins |
| 73 | + self.allow_all_headers = allow_all_headers |
| 74 | + self.preflight_explicit_allow_origin = preflight_explicit_allow_origin |
| 75 | + self.allow_origin_regex = compiled_allow_origin_regex |
| 76 | + self.simple_headers = simple_headers |
| 77 | + self.preflight_headers = preflight_headers |
| 78 | + |
| 79 | + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
| 80 | + if scope["type"] != "http": # pragma: no cover |
| 81 | + await self.app(scope, receive, send) |
| 82 | + return |
| 83 | + |
| 84 | + method = scope["method"] |
| 85 | + headers = Headers(scope=scope) |
| 86 | + origin = headers.get("origin") |
| 87 | + |
| 88 | + if origin is None: |
| 89 | + await self.app(scope, receive, send) |
| 90 | + return |
| 91 | + |
| 92 | + if method == "OPTIONS" and "access-control-request-method" in headers: |
| 93 | + response = self.preflight_response(request_headers=headers) |
| 94 | + await response(scope, receive, send) |
| 95 | + return |
| 96 | + |
| 97 | + await self.simple_response(scope, receive, send, request_headers=headers) |
| 98 | + |
| 99 | + def is_allowed_origin(self, origin: str) -> bool: |
| 100 | + if self.allow_all_origins: |
| 101 | + return True |
| 102 | + |
| 103 | + if self.allow_origin_regex is not None and self.allow_origin_regex.fullmatch(origin): |
| 104 | + return True |
| 105 | + |
| 106 | + return origin in self.allow_origins |
| 107 | + |
| 108 | + def preflight_response(self, request_headers: Headers) -> Response: |
| 109 | + requested_origin = request_headers["origin"] |
| 110 | + requested_method = request_headers["access-control-request-method"] |
| 111 | + requested_headers = request_headers.get("access-control-request-headers") |
| 112 | + |
| 113 | + headers = dict(self.preflight_headers) |
| 114 | + failures = [] |
| 115 | + |
| 116 | + if self.is_allowed_origin(origin=requested_origin): |
| 117 | + if self.preflight_explicit_allow_origin: |
| 118 | + # The "else" case is already accounted for in self.preflight_headers |
| 119 | + # and the value would be "*". |
| 120 | + headers["Access-Control-Allow-Origin"] = requested_origin |
| 121 | + else: |
| 122 | + failures.append("origin") |
| 123 | + |
| 124 | + if requested_method not in self.allow_methods: |
| 125 | + failures.append("method") |
| 126 | + |
| 127 | + # If we allow all headers, then we have to mirror back any requested |
| 128 | + # headers in the response. |
| 129 | + if self.allow_all_headers and requested_headers is not None: |
| 130 | + headers["Access-Control-Allow-Headers"] = requested_headers |
| 131 | + elif requested_headers is not None: |
| 132 | + for header in [h.lower() for h in requested_headers.split(",")]: |
| 133 | + if header.strip() not in self.allow_headers: |
| 134 | + failures.append("headers") |
| 135 | + break |
| 136 | + |
| 137 | + # We don't strictly need to use 400 responses here, since its up to |
| 138 | + # the browser to enforce the CORS policy, but its more informative |
| 139 | + # if we do. |
| 140 | + if failures: |
| 141 | + failure_text = "Disallowed CORS " + ", ".join(failures) |
| 142 | + return PlainTextResponse(failure_text, status_code=400, headers=headers) |
| 143 | + |
| 144 | + if PRIVATE: |
| 145 | + headers["Access-Control-Allow-Private-Network"] = "true" |
| 146 | + return PlainTextResponse("OK", status_code=200, headers=headers) |
| 147 | + |
| 148 | + async def simple_response(self, scope: Scope, receive: Receive, send: Send, request_headers: Headers) -> None: |
| 149 | + send = functools.partial(self.send, send=send, request_headers=request_headers) |
| 150 | + await self.app(scope, receive, send) |
| 151 | + |
| 152 | + async def send(self, message: Message, send: Send, request_headers: Headers) -> None: |
| 153 | + if message["type"] != "http.response.start": |
| 154 | + await send(message) |
| 155 | + return |
| 156 | + |
| 157 | + message.setdefault("headers", []) |
| 158 | + headers = MutableHeaders(scope=message) |
| 159 | + headers.update(self.simple_headers) |
| 160 | + origin = request_headers["Origin"] |
| 161 | + has_cookie = "cookie" in request_headers |
| 162 | + |
| 163 | + # If request includes any cookie headers, then we must respond |
| 164 | + # with the specific origin instead of '*'. |
| 165 | + if self.allow_all_origins and has_cookie: |
| 166 | + self.allow_explicit_origin(headers, origin) |
| 167 | + |
| 168 | + # If we only allow specific origins, then we have to mirror back |
| 169 | + # the Origin header in the response. |
| 170 | + elif not self.allow_all_origins and self.is_allowed_origin(origin=origin): |
| 171 | + self.allow_explicit_origin(headers, origin) |
| 172 | + |
| 173 | + await send(message) |
| 174 | + |
| 175 | + @staticmethod |
| 176 | + def allow_explicit_origin(headers: MutableHeaders, origin: str) -> None: |
| 177 | + headers["Access-Control-Allow-Origin"] = origin |
| 178 | + headers.add_vary_header("Origin") |
0 commit comments