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

add default CORS middleware #441

Merged
merged 3 commits into from
Aug 4, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 4 additions & 2 deletions stac_fastapi/api/stac_fastapi/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from starlette.responses import JSONResponse, Response

from stac_fastapi.api.errors import DEFAULT_STATUS_CODES, add_exception_handlers
from stac_fastapi.api.middleware import ProxyHeaderMiddleware
from stac_fastapi.api.middleware import CORSMiddleware, ProxyHeaderMiddleware
from stac_fastapi.api.models import (
APIRequest,
CollectionUri,
Expand Down Expand Up @@ -93,7 +93,9 @@ class StacApi:
pagination_extension = attr.ib(default=TokenPaginationExtension)
response_class: Type[Response] = attr.ib(default=JSONResponse)
middlewares: List = attr.ib(
default=attr.Factory(lambda: [BrotliMiddleware, ProxyHeaderMiddleware])
default=attr.Factory(
lambda: [BrotliMiddleware, CORSMiddleware, ProxyHeaderMiddleware]
)
)
route_dependencies: List[Tuple[List[Scope], List[Depends]]] = attr.ib(default=[])

Expand Down
38 changes: 37 additions & 1 deletion stac_fastapi/api/stac_fastapi/api/middleware.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,48 @@
"""api middleware."""

import re
import typing
from http.client import HTTP_PORT, HTTPS_PORT
from typing import List, Tuple

from starlette.middleware.cors import CORSMiddleware as _CORSMiddleware
from starlette.types import ASGIApp, Receive, Scope, Send


class CORSMiddleware(_CORSMiddleware):
"""
Subclass of Starlette's standard CORS middleware with default values set to those reccomended by the STAC API spec.

https://github.com/radiantearth/stac-api-spec/blob/914cf8108302e2ec734340080a45aaae4859bb63/implementation.md#cors
"""

def __init__(
self,
app: ASGIApp,
allow_origins: typing.Sequence[str] = ("*",),
allow_methods: typing.Sequence[str] = (
"OPTIONS",
"POST",
"GET",
),
allow_headers: typing.Sequence[str] = ("Content-Type",),
allow_credentials: bool = False,
allow_origin_regex: typing.Optional[str] = None,
expose_headers: typing.Sequence[str] = (),
max_age: int = 600,
) -> None:
"""Create CORS middleware."""
super().__init__(
app,
allow_origins,
allow_methods,
allow_headers,
allow_credentials,
allow_origin_regex,
expose_headers,
max_age,
)


class ProxyHeaderMiddleware:
"""
Account for forwarding headers when deriving base URL.
Expand Down