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

Convenience method to allow customizing route dependencies #295

Merged
merged 19 commits into from
Feb 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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: 6 additions & 0 deletions .github/workflows/cicd.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ jobs:
POSTGRES_HOST: localhost
POSTGRES_PORT: 5432

- name: Run test suite
run: |
cd stac_fastapi/api && pipenv run pytest -svvv
env:
ENVIRONMENT: testing

- name: Run test suite
run: |
cd stac_fastapi/sqlalchemy && pipenv run pytest -svvv
Expand Down
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

### Added

* Add hook to allow adding dependencies to routes. ([#295](https://github.com/stac-utils/stac-fastapi/pull/295))

### Changed

* update FastAPI requirement to allow version >=0.73 ([#337](https://github.com/stac-utils/stac-fastapi/pull/337))
Expand Down
43 changes: 33 additions & 10 deletions stac_fastapi/api/stac_fastapi/api/app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""fastapi app creation."""
from typing import Any, Callable, Dict, List, Optional, Type, Union
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union

import attr
from brotli_asgi import BrotliMiddleware
from fastapi import APIRouter, FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.params import Depends
from pydantic import BaseModel
from stac_pydantic import Collection, Item, ItemCollection
from stac_pydantic.api import ConformanceClasses, LandingPage
Expand All @@ -23,7 +24,12 @@
create_request_model,
)
from stac_fastapi.api.openapi import update_openapi
from stac_fastapi.api.routes import create_async_endpoint, create_sync_endpoint
from stac_fastapi.api.routes import (
Scope,
add_route_dependencies,
create_async_endpoint,
create_sync_endpoint,
)

# TODO: make this module not depend on `stac_fastapi.extensions`
from stac_fastapi.extensions.core import FieldsExtension, TokenPaginationExtension
Expand All @@ -42,19 +48,17 @@ class StacApi:

Attributes:
settings:
API settings and configuration, potentially using environment variables.
See https://pydantic-docs.helpmanual.io/usage/settings/.
API settings and configuration, potentially using environment variables. See https://pydantic-docs.helpmanual.io/usage/settings/.
client:
A subclass of `stac_api.clients.BaseCoreClient`. Defines the application logic which is injected
into the API.
A subclass of `stac_api.clients.BaseCoreClient`. Defines the application logic which is injected into the API.
extensions:
API extensions to include with the application. This may include official STAC extensions as well as
third-party add ons.
API extensions to include with the application. This may include official STAC extensions as well as third-party add ons.
exceptions:
Defines a global mapping between exceptions and status codes, allowing configuration of response behavior on
certain exceptions (https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers).
Defines a global mapping between exceptions and status codes, allowing configuration of response behavior on certain exceptions (https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers).
app:
The FastAPI application, defaults to a fresh application.
route_dependencies (list of tuples of route scope dicts (eg `{'path': '/collections', 'method': 'POST'}`) and list of dependencies (e.g. `[Depends(oauth2_scheme)]`)):
Applies specified dependencies to specified routes. This is useful for applying custom auth requirements to routes defined elsewhere in the application.
"""

settings: ApiSettings = attr.ib()
Expand Down Expand Up @@ -88,6 +92,7 @@ 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]))
route_dependencies: List[Tuple[List[Scope], List[Depends]]] = attr.ib(default=[])

def get_extension(self, extension: Type[ApiExtension]) -> Optional[ApiExtension]:
"""Get an extension.
Expand Down Expand Up @@ -337,6 +342,20 @@ async def ping():

self.app.include_router(mgmt_router, tags=["Liveliness/Readiness"])

def add_route_dependencies(
self, scopes: List[Scope], dependencies=List[Depends]
alukach marked this conversation as resolved.
Show resolved Hide resolved
) -> None:
"""Add custom dependencies to routes.

Args:
scopes: list of scopes. Each scope should be a dict with a `path` and `method` property.
dependencies: list of [FastAPI dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) to apply to each scope.

Returns:
None
"""
return add_route_dependencies(self.app.router.routes, scopes, dependencies)

def __attrs_post_init__(self):
"""Post-init hook.

Expand Down Expand Up @@ -378,3 +397,7 @@ def __attrs_post_init__(self):
# add middlewares
for middleware in self.middlewares:
self.app.add_middleware(middleware)

# customize route dependencies
for scopes, dependencies in self.route_dependencies:
self.add_route_dependencies(scopes=scopes, dependencies=dependencies)
50 changes: 48 additions & 2 deletions stac_fastapi/api/stac_fastapi/api/routes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""route factories."""
from typing import Any, Callable, Dict, Type, Union
from typing import Any, Callable, Dict, List, Optional, Type, TypedDict, Union

from fastapi import Depends
from fastapi import Depends, params
from fastapi.dependencies.utils import get_parameterless_sub_dependant
from pydantic import BaseModel
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import BaseRoute, Match

from stac_fastapi.api.models import APIRequest

Expand Down Expand Up @@ -94,3 +96,47 @@ def _endpoint(
return _wrap_response(func(request_data, request=request), response_class)

return _endpoint


class Scope(TypedDict, total=False):
"""More strict version of Starlette's Scope."""

# https://github.com/encode/starlette/blob/6af5c515e0a896cbf3f86ee043b88f6c24200bcf/starlette/types.py#L3
path: str
method: str
type: Optional[str]


def add_route_dependencies(
routes: List[BaseRoute], scopes: List[Scope], dependencies=List[params.Depends]
) -> None:
"""Add dependencies to routes.

Allows a developer to add dependencies to a route after the route has been
defined.

Returns:
None
"""
for scope in scopes:
for route in routes:

match, _ = route.matches({"type": "http", **scope})
if match != Match.FULL:
continue

# Mimicking how APIRoute handles dependencies:
# https://github.com/tiangolo/fastapi/blob/1760da0efa55585c19835d81afa8ca386036c325/fastapi/routing.py#L408-L412
for depends in dependencies[::-1]:
route.dependant.dependencies.insert(
vincentsarago marked this conversation as resolved.
Show resolved Hide resolved
0,
get_parameterless_sub_dependant(
depends=depends, path=route.path_format
vincentsarago marked this conversation as resolved.
Show resolved Hide resolved
),
)

# Register dependencies directly on route so that they aren't ignored if
# the routes are later associated with an app (e.g. app.include_router(router))
# https://github.com/tiangolo/fastapi/blob/58ab733f19846b4875c5b79bfb1f4d1cb7f4823f/fastapi/applications.py#L337-L360
# https://github.com/tiangolo/fastapi/blob/58ab733f19846b4875c5b79bfb1f4d1cb7f4823f/fastapi/routing.py#L677-L678
route.dependencies.extend(dependencies)
131 changes: 131 additions & 0 deletions stac_fastapi/api/tests/test_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
from fastapi import Depends, HTTPException, security, status
from starlette.testclient import TestClient

from stac_fastapi.api.app import StacApi
from stac_fastapi.extensions.core import TokenPaginationExtension, TransactionExtension
from stac_fastapi.types import config, core


class TestRouteDependencies:
@staticmethod
def _build_api(**overrides):
settings = config.ApiSettings()
return StacApi(
**{
"settings": settings,
"client": DummyCoreClient(),
"extensions": [
TransactionExtension(
client=DummyTransactionsClient(), settings=settings
),
TokenPaginationExtension(),
],
**overrides,
}
)

@staticmethod
def _assert_dependency_applied(api, routes):
with TestClient(api.app) as client:
for route in routes:
response = getattr(client, route["method"].lower())(route["path"])
assert (
response.status_code == 401
), "Unauthenticated requests should be rejected"
assert response.json() == {"detail": "Not authenticated"}

make_request = getattr(client, route["method"].lower())
path = route["path"].format(
collectionId="test_collection", itemId="test_item"
)
response = make_request(
path,
auth=("bob", "dobbs"),
data='{"dummy": "payload"}',
headers={"content-type": "application/json"},
)
assert (
response.status_code == 200
), "Authenticated requests should be accepted"
assert response.json() == "dummy response"

def test_build_api_with_route_dependencies(self):
routes = [
{"path": "/collections", "method": "POST"},
{"path": "/collections", "method": "PUT"},
{"path": "/collections/{collectionId}", "method": "DELETE"},
{"path": "/collections/{collectionId}/items", "method": "POST"},
{"path": "/collections/{collectionId}/items", "method": "PUT"},
{"path": "/collections/{collectionId}/items/{itemId}", "method": "DELETE"},
]
dependencies = [Depends(must_be_bob)]
api = self._build_api(route_dependencies=[(routes, dependencies)])
self._assert_dependency_applied(api, routes)

def test_add_route_dependencies_after_building_api(self):
routes = [
{"path": "/collections", "method": "POST"},
{"path": "/collections", "method": "PUT"},
{"path": "/collections/{collectionId}", "method": "DELETE"},
{"path": "/collections/{collectionId}/items", "method": "POST"},
{"path": "/collections/{collectionId}/items", "method": "PUT"},
{"path": "/collections/{collectionId}/items/{itemId}", "method": "DELETE"},
]
api = self._build_api()
api.add_route_dependencies(scopes=routes, dependencies=[Depends(must_be_bob)])
self._assert_dependency_applied(api, routes)


class DummyCoreClient(core.BaseCoreClient):
def all_collections(self, *args, **kwargs):
...

def get_collection(self, *args, **kwargs):
...

def get_item(self, *args, **kwargs):
...

def get_search(self, *args, **kwargs):
...

def post_search(self, *args, **kwargs):
...

def item_collection(self, *args, **kwargs):
...


class DummyTransactionsClient(core.BaseTransactionsClient):
"""Defines a pattern for implementing the STAC transaction extension."""

def create_item(self, *args, **kwargs):
return "dummy response"

def update_item(self, *args, **kwargs):
return "dummy response"

def delete_item(self, *args, **kwargs):
return "dummy response"

def create_collection(self, *args, **kwargs):
return "dummy response"

def update_collection(self, *args, **kwargs):
return "dummy response"

def delete_collection(self, *args, **kwargs):
return "dummy response"


def must_be_bob(
credentials: security.HTTPBasicCredentials = Depends(security.HTTPBasic()),
):
if credentials.username == "bob":
return True

raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="You're not Bob",
headers={"WWW-Authenticate": "Basic"},
)