service.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # (c) Nelen & Schuurmans
  2. import logging
  3. from typing import Any
  4. from typing import Callable
  5. from typing import Dict
  6. from typing import List
  7. from typing import Optional
  8. from typing import Set
  9. from asgiref.sync import sync_to_async
  10. from fastapi import Depends
  11. from fastapi import FastAPI
  12. from fastapi import Request
  13. from fastapi.exceptions import HTTPException
  14. from fastapi.exceptions import RequestValidationError
  15. from fastapi.security import OAuth2AuthorizationCodeBearer
  16. from starlette.status import HTTP_401_UNAUTHORIZED
  17. from starlette.status import HTTP_403_FORBIDDEN
  18. from starlette.types import ASGIApp
  19. from clean_python import Conflict
  20. from clean_python import DoesNotExist
  21. from clean_python import Gateway
  22. from clean_python import PermissionDenied
  23. from clean_python import Unauthorized
  24. from clean_python.oauth2 import OAuth2AccessTokenVerifier
  25. from clean_python.oauth2 import OAuth2Settings
  26. from .context import RequestMiddleware
  27. from .error_responses import BadRequest
  28. from .error_responses import conflict_handler
  29. from .error_responses import DefaultErrorResponse
  30. from .error_responses import not_found_handler
  31. from .error_responses import not_implemented_handler
  32. from .error_responses import permission_denied_handler
  33. from .error_responses import unauthorized_handler
  34. from .error_responses import validation_error_handler
  35. from .error_responses import ValidationErrorResponse
  36. from .fastapi_access_logger import FastAPIAccessLogger
  37. from .resource import APIVersion
  38. from .resource import clean_resources
  39. from .resource import Resource
  40. logger = logging.getLogger(__name__)
  41. class OAuth2Dependable(OAuth2AuthorizationCodeBearer):
  42. """A fastapi 'dependable' configuring OAuth2.
  43. This does two things:
  44. - Verify the token in each request
  45. - (through FastAPI magic) add the scheme to the OpenAPI spec
  46. """
  47. def __init__(self, scope, settings: OAuth2Settings):
  48. self.verifier = sync_to_async(
  49. OAuth2AccessTokenVerifier(
  50. scope,
  51. issuer=settings.issuer,
  52. resource_server_id=settings.resource_server_id,
  53. algorithms=settings.algorithms,
  54. admin_users=settings.admin_users,
  55. ),
  56. thread_sensitive=False,
  57. )
  58. super().__init__(
  59. authorizationUrl=settings.authorization_url,
  60. tokenUrl=settings.token_url,
  61. scopes={
  62. f"{settings.resource_server_id}*:readwrite": "Full read/write access"
  63. },
  64. )
  65. async def __call__(self, request: Request) -> None:
  66. token = await super().__call__(request)
  67. try:
  68. await self.verifier(token)
  69. except Unauthorized:
  70. raise HTTPException(status_code=HTTP_401_UNAUTHORIZED)
  71. except PermissionDenied:
  72. raise HTTPException(status_code=HTTP_403_FORBIDDEN)
  73. def fastapi_oauth_kwargs(auth: Optional[OAuth2Settings]) -> Dict:
  74. if auth is None:
  75. return {}
  76. return {
  77. "dependencies": [Depends(OAuth2Dependable(scope="*:readwrite", settings=auth))],
  78. "swagger_ui_init_oauth": {
  79. "clientId": auth.client_id,
  80. "usePkceWithAuthorizationCodeGrant": True,
  81. },
  82. }
  83. async def health_check():
  84. """Simple health check route"""
  85. return {"health": "OK"}
  86. class Service:
  87. resources: List[Resource]
  88. def __init__(self, *args: Resource):
  89. self.resources = clean_resources(args)
  90. @property
  91. def versions(self) -> Set[APIVersion]:
  92. return set([x.version for x in self.resources])
  93. def _create_root_app(
  94. self,
  95. title: str,
  96. description: str,
  97. hostname: str,
  98. on_startup: Optional[List[Callable[[], Any]]] = None,
  99. access_logger_gateway: Optional[Gateway] = None,
  100. ) -> FastAPI:
  101. app = FastAPI(
  102. title=title,
  103. description=description,
  104. on_startup=on_startup,
  105. servers=[
  106. {"url": f"{x.prefix}", "description": x.description}
  107. for x in self.versions
  108. ],
  109. root_path_in_servers=False,
  110. )
  111. app.middleware("http")(
  112. FastAPIAccessLogger(
  113. hostname=hostname, gateway_override=access_logger_gateway
  114. )
  115. )
  116. app.add_middleware(RequestMiddleware)
  117. app.get("/health", include_in_schema=False)(health_check)
  118. return app
  119. def _create_versioned_app(self, version: APIVersion, **kwargs) -> FastAPI:
  120. resources = [x for x in self.resources if x.version == version]
  121. app = FastAPI(
  122. version=version.prefix,
  123. tags=sorted(
  124. [x.get_openapi_tag().dict() for x in resources], key=lambda x: x["name"]
  125. ),
  126. **kwargs,
  127. )
  128. for resource in resources:
  129. app.include_router(
  130. resource.get_router(
  131. version,
  132. responses={
  133. "400": {"model": ValidationErrorResponse},
  134. "default": {"model": DefaultErrorResponse},
  135. },
  136. )
  137. )
  138. app.add_exception_handler(DoesNotExist, not_found_handler)
  139. app.add_exception_handler(Conflict, conflict_handler)
  140. app.add_exception_handler(RequestValidationError, validation_error_handler)
  141. app.add_exception_handler(BadRequest, validation_error_handler)
  142. app.add_exception_handler(NotImplementedError, not_implemented_handler)
  143. app.add_exception_handler(PermissionDenied, permission_denied_handler)
  144. app.add_exception_handler(Unauthorized, unauthorized_handler)
  145. return app
  146. def create_app(
  147. self,
  148. title: str,
  149. description: str,
  150. hostname: str,
  151. auth: Optional[OAuth2Settings] = None,
  152. on_startup: Optional[List[Callable[[], Any]]] = None,
  153. access_logger_gateway: Optional[Gateway] = None,
  154. ) -> ASGIApp:
  155. app = self._create_root_app(
  156. title=title,
  157. description=description,
  158. hostname=hostname,
  159. on_startup=on_startup,
  160. access_logger_gateway=access_logger_gateway,
  161. )
  162. kwargs = {
  163. "title": title,
  164. "description": description,
  165. **fastapi_oauth_kwargs(auth),
  166. }
  167. versioned_apps = {
  168. v: self._create_versioned_app(v, **kwargs) for v in self.versions
  169. }
  170. for v, versioned_app in versioned_apps.items():
  171. app.mount("/" + v.prefix, versioned_app)
  172. return app